0
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
}
1
  • Show us what you tried so far? There are a lot of example in the documentation here Commented Nov 5, 2017 at 8:26

1 Answer 1

1
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'.

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

2 Comments

Shouldn't it be .filter(User_id__id=1)?
@dm295 no.. it's just User_id_id

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.