JEEND0
JEEND0

Reputation: 482

Django post_save signal seemingly triggered only on 2nd save or after

So I'm using a signal-triggered function on post_save to create instances of another model when the the first is saved:

The model triggering the signal:

class Product(models.Model):
    # ...
    colors = models.ManyToManyField(Color)
    sizes = models.ManyToManyField(Size)

And the function:

def create_skus(instance, **kwargs):
    for color in instance.colors.select_related():
        for size in instance.colors.select_related():
            SKU.objects.get_or_create(product=instance, color=color, size=size)

My issue is that create_skus should be called on post_save every time, but only seems to work on the 2nd save or after, resulting in users have to save a Product twice. What is the origin of this?

EDIT: I think this has something to do with how these M2M relations are added (i.e. instance.colors.add(<Color object>) but I'm not sure, and if you know of a workaround, I'd love you forever.

Upvotes: 1

Views: 1847

Answers (1)

Mathieu Dhondt
Mathieu Dhondt

Reputation: 8914

The signal is sent when the Product instance is saved, not when the Color and Size instances are saved. Therefore, on the first try, your post_save() function's Product instance will not (yet) have the Color and Size instances, as they are not saved through the Product model's save() method.

Check out these two links:

Upvotes: 2

Related Questions