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 (ie instance.colors.add(<Color object>) but I'm not sure, and if you know of a workaround, I'd love you forever.


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:

  • A possible solution posted by a fellow SO'er
  • You could also work with the m2m_changed signal.
  • 链接地址: http://www.djcxy.com/p/54168.html

    上一篇: 将django模型实例保存到另一个模型中

    下一篇: 保存信号似乎只在第二次保存或之后触发