python - Django : Change default value for an extended model class

标签 python django django-models

我之前发布过一个类似的问题,但这个问题不同。我有一个相关类的模型结构,例如:

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 的默认值。我应该如何实现?

最佳答案

首先,在继承的这种使用中(至少根据我的测试)不可能更改子类中字段的默认值。 MathQuestionQuestion 在这里共享同一个字段,更改子类中的默认值会影响父类中的字段。

现在,如果 MathQuestionQuestion 之间的唯一区别是行为(因此,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/

相关文章:

python可执行文件不断崩溃

python - Django - 获取 pre_save 信号中的 auto_now 字段

python - Heroku 上的 Django 应用 : Application Error

python - 尽管在设置中指定了日期格式,但运行测试时 Django 仍给出 "invalid date format"错误

django - 一对一和外键关系之间的区别?

python:将元素插入到元组列表内的元组中

python - 如何在 python 中规范化音频文件的音量?

python - Django:在 __init__ 或保存函数中访问和更新表单类的字段

python - 'getattr() : attribute name must be string' error in admin panel for a model with an ImageField

python - 如何向用户输出力量?