[Answer]-Set field with content of associated objects on creation

1๐Ÿ‘

โœ…

As far as I understand you use inlines to edit MyClass.others field in the admin. If so then you can override ModelAdmin.save_related() method to update MyClass instance after the saving of M2M inlines.

class MyClass(models.Model):
    ....
    def save(self, force_insert=False, force_update=False, using=None):
        self.hash = self.generate_hash() if self.pk else 'NO-HASH-YET' 
        super(MyClass, self).save(force_insert, force_update, using)

class MyClassAdmin(admin.ModelAdmin):

    def save_related(self, request, form, formsets, change):
        # save M2M with `through` attribute
        super(MyClassAdmin, self).save_related(request, form, formsets, change)
        # update `MyModel` instance to regenerate hash
        form.instance.save()
๐Ÿ‘คcatavaran

Leave a comment