2011-02-05 66 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在这里共享相同的字段,更改子类中的默认值会影响父类中的字段。

现在,如果只什么和MathQuestion之间Question是不同的行为(所以,MathQuestion不添加除了那些在Question定义的任何字段),那么你可以把一个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 2011-02-05 01:12:14

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

使用FormModelForm,可以在其上覆盖的领域。对于模型,设置默认值是__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 

注意这调用父类初始化之后进行

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