5

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 は、多対 1 の関係である ForeignKey を使用するため、Choice を複数の Poll に使用できるはずです。これをフィクスチャからロードしようとすると、次のようになります。

[
    {
        "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."]

フィクスチャから多対 1 のリレーションをロードするにはどうすればよいですか?

4

2 に答える 2

4

チュートリアルからの引用は次のとおりです。

最後に、ForeignKey を使用して関係が定義されていることに注意してください。これは、Django に各 Choice が 1 つの Poll に関連していることを伝えます。Django は、多対 1、多対多、および 1 対 1 など、一般的なデータベース関係をすべてサポートしています。

それぞれ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."
    }
}

それが役立つことを願っています。

于 2013-07-29T08:52:16.710 に答える