bballboy8
bballboy8

Reputation: 450

How do you edit a many to many field in Django during save?

I currently have a model that looks like this

class Sector():
    featured_companies = models.ManyToManyField('Company', related_name='sectors')

    def save(self, **kwargs):
        super(Sector, self).save(**kwargs)
        for company in self.featured_companies.all():
            company.is_active = True
            company.save()

I know that this doesn't work because of the way Django works on save. I read in another post that adding something like this to the admin should work:

    def save_model(self, request, obj, form, change):
        if obj.featured_companies:
            form.cleaned_data['featured_companies'] = obj.featured_companies.all()
        super(SectorAdmin, self).save_model(request, obj, form, change)

However, it is still not working. How would I accomplish editing the many to many field during the save process?

Upvotes: 1

Views: 497

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476719

You can override the save_related(…) method [Django-doc] of your ModelAdmin and set the is_active field to True with a single query:

class SectorAdmin(ModelAdmin):

    # …

    def save_related(self, request, form, formsets, change):
        super().save_related(request, form, formsets, change)
        form.instance.featured_companies.all().update(
            is_active=True
        )

Upvotes: 1

Related Questions