鉴于此模型:
class Piece(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(blank=True, null=True)
favorited = models.ManyToManyField(User, through='FavoritedPieces', blank=True, null=True)
class FavoritedPieces(models.Model):
user = models.ForeignKey(User)
piece = models.ForeignKey(Piece)
created_at = models.DateTimeField(auto_now_add=True)
我怎样才能得到一个额外字段“favorited”的所有条目的列表,是真是假?这取决于用户是否将其标记为favorited
示例: 我有一张10件的单子。用户喜欢其中3个。当我打印列表时,我还需要打印该作品是否受到该用户的喜爱
List: [ <Piece1: name.. description.. favorited:False>,
<Piece2: name.. description.. favorited:False>,
<Piece3: name.. description.. favorited:True>,
]
我不想列一个新的问题列表:How to compare lists and get total matching items count
我想要类似的东西:MyModel.objects.annotate(total_likes=Sum('piece__total_likes'))
哪种方法最好
我建议你这样做:
pieces = Piece.objects.annotate(favorites_count=Count('FavoritedPieces'))
然后当你检查你的结果时,你可以做:
if piece.favorites_count > 0:
我知道这不是你想要的,但我觉得很简单
使用^{} :
这将给您一个额外的字段
'was_favorited'
。然而,如果你所做的只是检查作品是否受欢迎,有更简单的方法:测试字段本身:
如果确实需要该布尔值,请添加属性
was_favorited()
:相关问题 更多 >
编程相关推荐