Search code examples
pythondjangoormdjango-rest-frameworkmodels

Get data from 2 Model in Django python


class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.FloatField()
    avgrating = models.FloatField()
    def __str__(self):
        return self.name

class Rating(models.Model):
    Product_id = models.ForeignKey('Product', related_name='Product_id')
    User_id = models.ForeignKey('User', related_name='User_id')
    rate = models.IntegerField()

I want like - name of the product - price of the product - avgrating (AVG rating) - depend on User_id and Product_id and

SQL query like:

select p.name,p.price,p.avgrating,r.rate from Product p, Rating r where User_id=1;

out Like:

in json formate

{
  "name":"Iphone 8",
  "Price":80000,
  "avgrating":3.5,
  "rate":5
}

Solution

  • results = Rating.objects.filter(User_id_id = 1)
    data = []
    for res in results:
        data.append( {
              "name": res.Product_id.name,
              "Price": res.Product_id.price,
              "avgrating": res.Product_id.avgrating,
              "rate": res.rate
        })
    

    Why did i use User_id_id?

    Beacuse, Django appends '_id' for all names related to keys. So if you are using the key value directly, use '_id'.