Django saving many to many entries using generic views

点点圈 提交于 2019-12-11 04:18:49

问题


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')

and my views has:

class SponsorEdit(UpdateView):
    model = Sponsor
    template_name = 'sponsoredit.html'
    fields = ('account', 'department', 'exp_date', 'last_name', 'first_name', 'signature_code', 'comments', 'product', 'accounts')

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.

Where is the issue?


回答1:


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)


来源:https://stackoverflow.com/questions/30600764/django-saving-many-to-many-entries-using-generic-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!