我正在使用django 1.4,我有以下型号:
class Newsletter(EmailTemplate):
receivers = models.ManyToManyField(User, related_name='newsletters',
db_index=True,
through='NewsletterReceiver')
class EmailReceiver(models.Model):
user = models.ForeignKey(User, db_index=True)
class NewsletterReceiver(EmailReceiver):
newsletter = models.ForeignKey(Newsletter, db_index=True)
当我在我的视图中通过执行以下操作创建Newsletter
对象时:
newsletter = form.save(commit=False)
newsletter.receivers.clear()
receivers = form.cleaned_data['receivers']
for receiver in receivers:
newsletter_receiver = NewsletterReceiver(user=receiver, newsletter=newsletter)
newsletter_receiver.save()
form.save_m2m()
newsletter.save()
我可以看到Newsletter
对象和NewsletterReceiver
对象都已创建。如果我从新创建的ipython
查询user
和newsletter
,则使用NewsletterReceiver
一切正常,但如果我从Newsletter
实例查询接收器然后django抱怨我不明白的事情:
In [2]: nr = NewsletterReceiver.objects.all()[0]
In [3]: nr.user
Out[3]: <User: 3>
In [4]: nr.newsletter
Out[4]: <Newsletter: Newsletter object>
In [5]: nr.newsletter.receivers
Out[5]: <django.db.models.fields.related.ManyRelatedManager at 0x10ea26f90>
In [6]: nr.newsletter.receivers.all()
Out[6]:
<repr(<django.db.models.query.QuerySet at 0x10ee860d0>) failed:
django.db.utils.DatabaseError: column web_newsletterreceiver.user_id does not exist
LINE 1: ...N "web_newsletterreceiver" ON ("auth_user"."id" = "web_newsl...
^
>
这是因为目标模型的ForeignKey
是继承的吗?是否有解决方法或我是否必须重构模型?
答案 0 :(得分:0)
one2many
, primary_key
关系将成为可能。就像你加入2个表一样,你必须按连接顺序给出primary_key。
请在模型中添加一个主键。
当您尝试使用all()
函数检索数据时,它会尝试加入主键。
答案 1 :(得分:0)
我通过添加:
解决了这个问题class Meta:
abstract = True
到EmailReceiver
模型。