U
U
un1t2015-10-13 12:06:31
Django
un1t, 2015-10-13 12:06:31

Why is m2m_changed called when there is no connection yet?

There are two related models

class Tag(models.Model):
    pass

class Photo(models.Model):
    tags = models.ManyToManyField(Tag, related_name='tags', blank=True)

This is how I end up:
@receiver(m2m_changed, sender=Photo.tags.through)
def photo_tags_changed(sender, instance, action, **kwargs):
    print( action, kwargs, instance.tags.all())

print output
post_add {'pk_set': {28538}, 'using': 'default', 'reverse': False, 'model': <class 'apps.photos.models.Tag'>, 'signal': <django.db.models.signals.ModelSignal object at 0x7fc890ddda20>} []

As far as I understand, the "post_add" action should take place after the link has been added.
However, a new tag is passed to pk_set, but if you do instance.tags.all(), then the link has not yet been created. I thought maybe something was cached in the ORM, but at that moment I checked in the database, there is no connection yet.
I am using DRF, the serializer looks like this:
class PhotoWriteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo

It seems that DRF is somehow affected, tk. if you add tags from the console without it, then there are already links in post_add.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
un1t, 2015-10-16
@un1t

In general, this bug is related to this.
Why does Djnago Rest Framework return old information about related objects on update?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question