[Answered ]-Proper way to annotate favorited items

1👍

I would recommend doing something like this:

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

And then when you go through your results, you can do:
if piece.favorites_count > 0:

I know it’s not exactly what you were looking for, but I think it’s simple enough.

1👍

Using extra():

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

This will give you an extra field 'was_favorited'. However, if all you’re doing is checking whether or not the Piece was favorited, there are much simpler ways of doing this:

Test the field itself:

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

If you really need that boolean, add a property 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

Leave a comment