I have a model Event
which has a ManyToManyField
named users. I want to get all the events with an extra attribute which denotes whether a specific user belongs to this event or not.
class Event(models.Model):
users = models.ManyToManyField(User)
# Expected code format
user = User.objects.get(id=1)
events = // Event query
print events[0].your_event // It should be True if above user is part of this event else False
Here is the code which I tried
from django.db.models import Case, When, BooleanField
user = User.objects.get(id=1)
Event.objects.annotate(your_event=Case(when(users=user, then=True), default=False, output_field=BooleanField()))
Problem with above code: If an Event
object has multiple users (let 4) then it is returning 4 objects which has your_event
as False
in three objects and True
in one object. But I want only object for each
event.
I believe a better solution can exist for this purpose.