Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create relationships between 3 models in django?

I’m building a marketplace that have 2 user types i.e. buyers and sellers.

Now I want to create a relationship model between buyers, sellers and OrderedItems, so that the sellers gets notified once the buyers orders an item.

This is the model I made:

class Ordered(models.Model):
    ordered_items = models.ManyToManyField(Cart)
    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)

But I don’t know how to implement this in views.py
Any suggestion will be really helpful

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you

>Solution :

As per the current model relation you can use pre_save or post-save signals on ordered model. Whenever you update a new value(item added by buyer) in ordered_items(many-to-many relation) you can send a mail to seller linked with that buyer. That mailing part will be defined inside pre or post signals .

In views.py you will get input parameters as follows -:

  • seller_id
  • ordered_item
  • buyer_id

And you will search for seller_id and buyer_id combination using filter statement in Ordered model and set ordered_item in that field. After that model save function will be called and after that post_save signal will be triggered and will send the mail to seller.

There will be 2 conditions for this scenario -:

  1. Either you create a new value if user is buying his/her first item.
  2. Buyer is adding another item in cart. In this case you will update the existing value.
    In Either case model’s save function will automatically be initiated.

Reference -:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading