正确的方法来注释喜欢的项目

2024-09-22 10:21:42 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于此模型:

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

哪种方法最好


Tags: 用户nametrue列表piecemodelmodelsdescription
2条回答

我建议你这样做:

pieces = Piece.objects.annotate(favorites_count=Count('FavoritedPieces'))

然后当你检查你的结果时,你可以做: if piece.favorites_count > 0:

我知道这不是你想要的,但我觉得很简单

使用^{}

Piece.objects.extra(select={'was_favorited': '''
    SELECT
        CASE WHEN id IS NULL THEN false ELSE true END
    FROM appname_favoritedpieces
        WHERE appname_favoritedpieces.piece_id = appname_piece.id
'''})

这将给您一个额外的字段'was_favorited'。然而,如果你所做的只是检查作品是否受欢迎,有更简单的方法:

测试字段本身:

for p in Piece.objects.all():
    if p.favorited:
        pass  # do something if the Piece was favorited

如果确实需要该布尔值,请添加属性was_favorited()

class Piece(models.Model):
    ...

    @property
    def was_favorited(self):
        return true if self.favorited else false


# then you can call this property on Piece objects:
>>> Piece.objects.get(name="No one's favorite").was_favorited
False

相关问题 更多 >