I am trying to implement a basic 'favourites' system based on a foreign key table.
Let's say I have the following simple models:
class Item(models.Model)
id = models.IntegerField()
class User(models.Model)
id = models.IntegerField()
class UserFavourites(models.Model)
user = models.ForeignKey(User, related_name='user_for_fav_rel')
item = models.ForeignKey(Item, related_name='item_for_fav_rel')
Now I generate the following queryset for items to see if they have been marked as a favourite by the user:
queryset = Item.objects.all()
USER_ID = request.user.id
queryset = queryset.annotate(
favourite=Case(
When(
item_for_fav_rel__user__id=USER_ID,
then=Value('True')
),
default=Value('False'),
output_field=BooleanField()
)
)
All of this works great, but in the response, if the item has indeed been favourited, I receive a duplicate of that particular item in the queryset. Any idea how to avoid this?
Resultant SQL Query (edited down to the minimal example I think...)
SELECT
"core_item"."id",
CASE
WHEN "core_userfavourites"."user_id" = 1 THEN True
ELSE False
END AS "favourite"
FROM "core_item"
LEFT OUTER JOIN "core_userfavourites"
ON ("core_item"."id" = "core_userfavourites"."item_id")