加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Django中加载具有多对一关系的夹具

发布时间:2020-12-16 21:37:08 所属栏目:Python 来源:网络整理
导读:djangoproject.com上的Django教程给出了这样的模型: import datetimefrom django.utils import timezonefrom django.db import modelsclass Poll(models.Model): question = models.CharField(max_length = 200) pub_date = models.DateTimeField('date pub
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,这是一种多对一的关系,所以我应该能够使用一个选择进行多个轮询.如果我尝试从夹具中加载它,如下所示:

[
    {
        "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?",{
        "model": "polls.Choice","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","fields": {
            "poll": [3,4],"votes": 0
        }
    }

我收到此错误:

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

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

解决方法

这是教程中的引用:

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,"choice_text": "Not so good."
    }
}

希望有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读