从Django python中的2 Model获取数据

时间:2017-11-05 08:21:04

标签: python django orm django-rest-framework models

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()

我想要 - 产品名称 - 产品价格 - avgrating(AVG评级) - 取决于User_id和Product_id以及

SQL查询如:

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

out赞:

在json formate中

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

1 个答案:

答案 0 :(得分: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
    })

为什么我使用User_id_id?

Beacuse,Django为所有与密钥相关的名称附加'_id'。因此,如果您直接使用键值,请使用'_id'。