我之前发布过一个类似的问题,但这个问题不同。我有一个相关类的模型结构,例如:
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 的默认值。我应该如何实现?
最佳答案
首先,在继承的这种使用中(至少根据我的测试)不可能更改子类中字段的默认值。 MathQuestion
和 Question
在这里共享同一个字段,更改子类中的默认值会影响父类中的字段。
现在,如果 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
关于python - Django : Change default value for an extended model class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4904230/