给定此模型:

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”(额外)字段(真或假)的所有作品列表?这取决于用户是否将其标记为收藏。

例:
我有一个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:

我知道这并不是您要找的东西,但我认为这很简单。

关于python - 注释收藏项的正确方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24166620/

10-12 16:41