2011-02-05 17 views
12

これまでと同様の質問を投稿しましたが、これは以前とは異なります。django:拡張モデルクラスのデフォルト値を変更

class Question(models.Model): 
    ques_type = models.SmallIntegerField(default=TYPE1, Choices= CHOICE_TYPES) 

class MathQuestion(Question): 
    //Need to change default value of ques_type here 
    // Ex: ques_type = models.SmallIntegerField(default=TYPE2, Choices= CHOICE_TYPES) 

派生クラスのques_typeのデフォルト値を変更したいと思います。私はこれをどのように達成すべきですか?

答えて

8

まず、この継承の使用では、少なくとも私のテストによれば、子クラスのフィールドのデフォルトを変更することはできません。 MathQuestionQuestionは同じフィールドを共有します。子クラスのデフォルトを変更すると、親クラスのフィールドに影響します。何だけMathQuestionQuestionとの間で異なること(そう、MathQuestionQuestionで定義されたもの以外の任意のフィールドを追加しません)動作であれば

さて、あなたはそれproxy model作ることができます。そうすれば、MathQuestionのデータベーステーブルは作成されません。

from django.db import models 

class Question(models.Model): 
    ques_type = models.SmallIntegerField(default=2) 

class MathQuestion(Question): 

    def __init__(self, *args, **kwargs): 
     self._meta.get_field('ques_type').default = 3 
     super(MathQuestion, self).__init__(*args, **kwargs) 

    class Meta: 
     proxy = True 

テスト:

In [1]: from bar.models import * 

In [2]: a=Question.objects.create() 

In [3]: a.ques_type 
Out[3]: 2 

In [4]: b=MathQuestion.objects.create() 

In [5]: b.ques_type 
Out[5]: 3 
+2

派生クラスに新しいフィールドを追加しています。したがって、プロキシクラスメソッドは動作しません。 – Neo

+0

__init__メソッドでques_typeフィールドを設定できませんか? – Neo

+0

@ネオ私は試みましたが、[documentation](http://docs.djangoproject.com/ja/1.2/topics/db/models/#field-name-hiding-is-not-permitted)によると、これはありません** –

0

これはクロージャを使用して行うのは簡単です。

django.db輸入モデル

# You start here, but the default of 2 is not what you really want. 

class Question(models.Model): 
    ques_type = models.SmallIntegerField(default=2) 

class MathQuestion(Question): 

    def __init__(self, *args, **kwargs): 
     self._meta.get_field('ques_type').default = 3 
     super(MathQuestion, self).__init__(*args, **kwargs) 

    class Meta: 
     proxy = True 

から閉鎖は、あなたがそれを好きどのようにそれを定義することができます。

django.db輸入モデルから

def mkQuestion(cl_default=2): 
    class i_Question(models.Model): 
     ques_type = models.SmallIntegerField(default=cl_default) 

    class i_MathQuestion(i_Question): 

     def __init__(self, *args, **kwargs): 
      super(MathQuestion, self).__init__(*args, **kwargs) 
    return i_MATHQUESTION 


MathQuestion = mkQuestion() 
MathQuestionDef3 = mkQuestion(3) 

# Now feel free to instantiate away. 
1

あなたがフィールドを上書きすることができた上FormまたはModelFormを、使用してください。これはは、親クラスのinitを呼び出した後を行わなければならないこと

class Question(models.Model): 
    ques_type = models.SmallIntegerField(default=2) 

class MathQuestion(Question): 

    def __init__(self, *args, **kwargs): 
     super(MathQuestion, self).__init__(*args, **kwargs) 
     self.ques_type = 3 

    class Meta: 
     proxy = True 

注:それはそうのような__init__方法だでモデルの場合、デフォルト値を設定します。

https://docs.djangoproject.com/en/dev/topics/forms/modelforms/

関連する問題