Django查询ManyToManyField

时间:2011-07-07 12:28:45

标签: python django django-queryset django-orm

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique = True, related_name = 'user')
    likes = models.ManyToManyField(Product, null = True, blank = True)

class Product(models.Model):
    user = models.ForeignKey(User)
    price = models.FloatField(default = 0)

我已经:

p1 = Product.objects.get(pk = 1)

我想计算所有UserProfile对象中p1字段中包含likes次的次数。

如何?

1 个答案:

答案 0 :(得分:1)

UserProfile.objects.filter(likes=p1).count()

假设每个配置文件只能一次性浏览产品。