关于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用于多个投票。如果我尝试从固定装置加载此文件,例如:
[
    {
        "model": "polls.Poll",
        "pk": 3,
        "fields": {
            "question": "What time do you sleep?",
            "pub_date": "2013-07-29T10:00:00+00:00"
        }
    },
    {
        "model": "polls.Poll",
        "pk": 4,
        "fields": {
            "question": "What time do you get up?",
            "pub_date": "2013-07-29T10:00:00+00:00"
        }
    },
    {
        "model": "polls.Choice",
        "pk": 4,
        "fields": {
            "poll": [{"pk": 3}, {"pk": 4}],
            "choice_text": "10:00",
            "votes": 0
        }
    }
]

我收到此错误:
    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."]

如何从灯具加载多对一关系?

最佳答案

这是本教程的引文:



每个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."
    }
}

希望能有所帮助。

关于python - 在Django中以多对一关系加载夹具,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17919556/

10-12 06:15