开发者

Django query for ManyToManyField

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)

I've:

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

I want to count how many times p1 is contained in likes field in all UserProfil开发者_高级运维e objects.

How?


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

assuming that a product can only be liked one time by each profile.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜