1

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

4
  • Can yo7u share your Product model? I assume it has a FK to the SellerPorifle, right? Commented Jan 8, 2022 at 14:23
  • Yes, The product model has a foreignkey to the sellerprofile Commented Jan 8, 2022 at 15:51
  • Can you add the Products model? Please edit the question. Commented Jan 8, 2022 at 16:29
  • Is this change fine? Or do I need to provide more codes? Commented Jan 8, 2022 at 16:50

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.