问题
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