Question

I have problem with 1 query connected with ManyToManyField. We have 2 related models: User and Event. Model Event has 2 relations with User, it must have 1 organizer and any number or participants - organizer cannot be participant (I skipped the code which is responsible for validation of that). Now, as an example, what I want is all participants from events I organized. Problem is that below query only gets request.user himself, skipping all participants alltogether. Is there a way to achieve what I need without any custom query? thanks

#models.py

class User(models.Model):
    name = models.CharField(max_length=100)

class Event(models.Model):
    name = models.CharField(max_length=100)
    organiser = models.ForeignKey(User)
    participants = models.ManyToManyField(User, related_name='participants', blank=True, null=True)

#views.py

def assess_partners(request):
    users = User.objects.filter(event__organizer=request.user)
    return render(request, 'some template.html', {'users': users})
Was it helpful?

Solution

Things will be clearer if you use better related_names, e.g.:

class Event(models.Model):
    name = models.CharField(max_length=100) 
    organiser = models.ForeignKey(User, related_name='events_as_organiser')
    participants = models.ManyToManyField(User, related_name='events_as_participant', blank=True)

what I want is all participants from events I organized

User.objects.filter(events_as_participant__organiser=request.user).distinct()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top