Search code examples
djangodjango-modelsdjango-signals

Django signal post_save update


I have an Article model that has a OnetoOne relationship with a Catalog model.

My current functionality has the Article model, on post_save, create a Catalog model with the same name. I would like to do another bit of functionality where the Article FK goes from being null to updating to the now available Catalog instance of the same name.

Here is what I have so far:

class Catalog(models.Model):
    name = models.CharField(max_length=100)
    price = models.IntegerField()

    def __unicode__(self):
        return self.name

class Article(models.Model):
    catalog = models.OneToOneField(Catalog, related_name='article_products', blank=True, null=True)
    title = models.CharField(max_length=200)

    def __unicode__(self):
        return unicode(self.title)

@receiver(post_save, sender=Article)
def create_catalog(sender, **kwargs):
    if kwargs.get('created', False):
        Catalog.objects.get_or_create(name=kwargs.get('instance'), price='10')

The above code is working correctly. Once the Article model instance is created it creates a Catalog instance of the same name. I'd like to now update the newly created Article with the FK relationship to the newly created Catalog instance. I think my logic below is close, but I can't get it to work.

@receiver(post_save, sender=Catalog)
def attach_catalog(sender, **kwargs):
    if kwargs.get('created', False):
        Article.objects.latest('id').update(catalog=kwargs.get('instance'))

Solution

  • I was able to get it working with the following:

    @receiver(post_save, sender=Catalog)
    def attach_catalog(sender, **kwargs):
        if kwargs.get('created', False):
            b = Article.objects.latest('id')
            Article.objects.filter(pk=b.id).update(catalog=kwargs.get('instance'))