Các Django hướng dẫn về djangoproject.com đưa ra một mô hình như thế này:tải cố định với nhiều-một mối quan hệ trong 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 sử dụng một ForeignKey, mà là một mối quan hệ với ai nhiều, vì vậy tôi nên có thể sử dụng Lựa chọn cho nhiều hơn một Cuộc thăm dò ý kiến. Nếu tôi cố gắng tải này từ một vật cố, như vậy:
[
{
"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
}
}
]
tôi nhận được lỗi này:
DeserializationError: Problem installing fixture '/.../poll/polls/fixtures/initial_data.json': [u"'[{u'pk': 3}, {u'pk': 4}]' value must be an integer."]
Hoặc vậy:
{
"model": "polls.Choice",
"pk": 4,
"fields": {
"poll": [3, 4],
"choice_text": "10:00",
"votes": 0
}
}
tôi nhận được lỗi này:
DeserializationError: Problem installing fixture '/.../poll/polls/fixtures/initial_data.json': [u"'[3, 4]' value must be an integer."]
Làm cách nào để có thể tải mối quan hệ nhiều-một một vật cố định?
Có điều đó đã giúp ích. Những gì tôi đã cố gắng làm là để làm một mối quan hệ nhiều-nhiều, sau khi thay đổi mô hình cho phù hợp, nó làm việc tốt bằng cách sử dụng cú pháp [1, 2]. Tôi bằng cách nào đó đã có mối quan hệ nhiều-một trong những đảo ngược trong đầu của tôi. – henrikstroem