Search code examples
djangodjango-modelsdjango-signals

Failed to create a seller instance using django signals


I'm building a website with 2 user types and still new to django. And I want to add the functionality to add the seller of the product whenever a product is sold. I'm sorry that I couldn't explain it better. Here's the code of models.py:

class Ordered(models.Model):
    products = models.ForeignKey(Products, on_delete = models.SET_NULL, null = True)
    seller = models.ForeignKey(SellerProfile, on_delete = models.SET_NULL, null = True)
    buyer = models.ForeignKey(CustomerProfile, on_delete = models.CASCADE)
    ordered_on = models.DateTimeField(auto_now_add = True)

product/models.py

class Products(models.Model):
    seller = models.ForeignKey(SellerProfile, on_delete = models.CASCADE)
    title = models.CharField(max_length = 255)
    product_category = models.CharField(choices = CATEGORY_CHOICES, max_length = 100, default = 'eBooks')
    description = models.TextField()
    files = models.FileField(upload_to = 'media/product_files/', null = True)
    slug = models.SlugField(max_length = 255, unique = True, null = True, blank = True)

And this is the signal code:

@receiver(post_save, sender = Ordered)
def new_order_for_seller(sender, instance, created, *args, **kwargs):
    seller = Ordered.seller.sellerprofile
    if created:
        Ordered.objects.create(seller = seller)

Any suggestion or correction of the code will be really helpful. Thank you


Solution

  • You can set the seller attribute as the instance.product.seller:

    @receiver(pre_save, sender = Ordered)
    def new_order_for_seller(sender, instance, created, *args, **kwargs):
        if created and instance.product is not None:
            instance.seller_id = instance.product.seller_id

    We can do this in a pre_save signal to prevent saving the new Ordered object a second time.

    That being said, since the seller is already determined by the Product, it does not make much sense to duplicate this, since it can eventually lead to inconsistencies where the Seller of a Product changes later, and the Ordered is still pointing to the "old" Seller.