6
This is how I worked around this, indeed baffling, behavior. Connect a signal receiver to models.signals.m2m_changed event, this get’s triggered each time a m2m field is changed. The inline comments explain why.
class Gig(models.Model):
def slugify(self):
# Add venue name, date and artists to slug
self.slug = slugify(self.venue.name) + "-"
self.slug += self.date.strftime("%d-%m-%Y") + "-"
self.slug += "-".join([slugify(artist.name) for artist in self.artists.all()])
self.save()
@receiver(models.signals.m2m_changed, sender=Gig.artist.through)
def gig_artists_changed(sender, instance, **kwargs):
# This callback function get's called twice.
# 1 first change appears to be adding an empty list
# 2nd change is adding the actual artists
if instance.artist.all() and not instance.slug:
instance.slugify()
1
That’s because m2m relation are saved after your model save, in order to obtain PK of parent object. In your case, second save works as expected because model already has PK and associated books from first save (it’s done in a signal).
I haven’t found the solution yet, best bet is to do your changes in admin view, i guess.
- [Django]-DJANGO allow access to a certain view only from a VPN Network
- [Django]-Django: export current queryset to csv by button click in browser
- [Django]-Boto3 deprecation warning on import
Source:stackexchange.com