Django Saves Many, Many Records Using Common Views

I have a django model with many, many fields:

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:

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 edit a record by adding some fields in the "Many in MAny" relationships, I get the following error:

AttributeError at /irms/sponsoredit/2
Cannot set values on a ManyToManyField which specifies an intermediary model.  Use irms.ProductSponsor Manager instead.

Where is the problem?

+2
source share
1 answer

In your model, you use AccountSponsorand ProductSponsor. They are user-defined staging tables for relationships, when you save an object Sponsor, you need to manually set the staging objects " ProductSponsor" and " AccountSponsor". Sort of:

ProductSponsor.objects.create(sponsor=SponsorObject, product=ProductObject)
AccountSponsor.objects.create(sponsor=SponsorObject, account=AccountObject)
0
source

All Articles