Django请求继承mod的父模型的默认链接

2024-09-29 23:25:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django应用程序中创建了一些模型来描述应用程序中存在的不同类型的投票。你知道吗

from django.db import models
from api.models.helpers import JSONSerializableModel
from api.models.speaker import Speaker
from api.models.auth import Attendee
from api.models.event import Event



class BasePoll(JSONSerializableModel, models.Model):

    text = models.CharField('text', max_length=300, blank=False)



class MultipleChoicePoll(JSONSerializableModel, models.Model):

    @property
    def results(self):
        results = multiplechoicepollresponse_set.all().annotate(Count('multiplechoicepollresponse'))
        return average_rating


class RatingPoll(BasePoll):
    @property
    def average(self):
        average_rating = ratingpollresponse_set.all().aggregate(Avg('rating'))
        print(average_rating)
        return average_rating


class OpenQuestionPoll(BasePoll): 
    pass

我已经完成了迁移,一切看起来都很好,但是现在当我尝试使用交互式shell时:

In [6]: poll = MultipleChoicePoll.objects.all()[0]

In [7]: poll.text = 'Some poll text'

In [8]: poll.save()

In [9]: poll = MultipleChoicePoll.objects.all()[0]

In [10]: poll.text
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-28f6dbcd48ba> in <module>()
----> 1 poll.text

AttributeError: 'MultipleChoicePoll' object has no attribute 'text'

现在,当我从BasePoll继承时,每个子模型都会得到一个自动BasePoll\u ptr One2One字段。但是,当我迁移时,它会询问这个字段的默认值,这是不可能的,因为这个字段是由Django创建的,而不是我:

    You are trying to add a non-nullable field 'basepoll_ptr' to multiplechoicepoll without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py

Tags: textinfromimportapimodelsallclass

热门问题