2

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.

Joe Holloway
  • 28,320
  • 15
  • 82
  • 92
SHIVAM JINDAL
  • 2,844
  • 1
  • 17
  • 34
  • Well I'm already surprised this works. I would expect that this would simply construct for every `Event` a number of copies (the number of users attached to it), and for every user, it would then denote whether it is *that* specific user. – Willem Van Onsem May 23 '18 at 20:20
  • @WillemVanOnsem You are right, it is returning multiple copies of the same Event, how can I overcome it? – SHIVAM JINDAL May 25 '18 at 17:57

0 Answers0