Django使用通用视图保存多个到多个条目 [英] Django saving many to many entries using generic views
本文介绍了Django使用通用视图保存多个到多个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个django模型,有很多到多个字段,如下所示:
I have a django model with many to many fields as follows:
class Sponsor(CommonInfo, Person):
signature_code = models.CharField(max_length=20, blank=True)
account = models.ForeignKey(Account)
department = models.ForeignKey(Department)
product = models.ManyToManyField(Product, null=True, blank=True, through = 'ProductSponsor')
accounts = models.ManyToManyField(Account, null=True, blank=True, through = 'AccountSponsor', related_name='sponsoraccounts')
,我的观点有:
class SponsorEdit(UpdateView):
model = Sponsor
template_name = 'sponsoredit.html'
fields = ('account', 'department', 'exp_date', 'last_name', 'first_name', 'signature_code', 'comments', 'product', 'accounts')
当我通过在许多中添加一些字段来编辑条目到MAny r elationship,我得到以下错误:
When i am editing an entry by adding some fields in the Many to MAny relationship, i get the following error:
AttributeError at /irms/sponsoredit/2
Cannot set values on a ManyToManyField which specifies an intermediary model. Use irms.ProductSponsor's Manager instead.
问题在哪里?
推荐答案
在您的模型中,您正在使用 AccountSponsor
和 ProductSponsor
。它们是关系的自定义中间表,当您保存赞助者
对象时,需要设置中间 AccountSponsor
'对象。如下所示:
In your model you are using AccountSponsor
and ProductSponsor
. They are custom intermediate tables for the relationship, when you save a Sponsor
object you need to set the intermediate 'ProductSponsor
' and 'AccountSponsor
' objects manually. Something like:
ProductSponsor.objects.create(sponsor=SponsorObject, product=ProductObject)
AccountSponsor.objects.create(sponsor=SponsorObject, account=AccountObject)
这篇关于Django使用通用视图保存多个到多个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文