Djang中具有多通关系的加载夹具

2024-06-06 19:42:41 发布

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

关于djangoproject.com的Django教程给出了这样一个模型:

import datetime
from django.utils import timezone
from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length = 200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days = 1) <= self.pub_date < now

    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length = 200)
    votes = models.IntegerField(default = 0)

    def __unicode__(self):
        return self.choice_text

Choice使用ForeignKey,这是一个多对一的关系,所以我应该能够使用Choice进行多个投票。如果我试着从固定装置中加载这个,比如:

^{pr2}$

我得到这个错误:

    DeserializationError: Problem installing fixture '/.../poll/polls/fixtures/initial_data.json': [u"'[{u'pk': 3}, {u'pk': 4}]' value must be an integer."]

大约:

{
        "model": "polls.Choice",
        "pk": 4,
        "fields": {
            "poll": [3, 4],
            "choice_text": "10:00",
            "votes": 0
        }
    }

我得到这个错误:

DeserializationError: Problem installing fixture '/.../poll/polls/fixtures/initial_data.json': [u"'[3, 4]' value must be an integer."]

如何从固定装置加载多对一关系?在


Tags: textimportselfdatereturnmodelsdefnow
1条回答
网友
1楼 · 发布于 2024-06-06 19:42:41

以下是本教程中的一句话:

Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is related to a single Poll. Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones.

每个Choice都与一个Poll相关,您正试图将一个键列表传递给Choice.poll字段。在

但是,每个民意测验都可以与几个选项相关:

{
    "pk": 4, 
    "model": "polls.Choice", 
    "fields": {
        "votes": 0, 
        "poll": 2, 
        "choice_text": "Meh."
    }
}, 
{
    "pk": 5, 
    "model": "polls.Choice", 
    "fields": {
        "votes": 0, 
        "poll": 2, 
        "choice_text": "Not so good."
    }
}

希望有帮助。在

相关问题 更多 >