Search code examples
pythondjangomanytomanyfield

How to get data from ManyToManyField - Django


I have a problem with retrieving data from this ManyToManyField (users) of a model Event:

class Event(models.Model):
    name = models.CharField(max_length=26)
    description = models.CharField(max_length=200)
    date = models.DateField()
    user = models.ForeignKey(User)
    users = models.ManyToManyField(User, related_name="users", blank=True)
    image = models.ImageField(
        upload_to='images/',
        default='images/default.png'
    )

users = models.ManyToManyField creates an additional table "events_event_users", It stores user_id and event_id fields. So I want to output all event information from Event model, where user_id from that additional table is equal to request.user. Please help, how should I do this?


Solution

  • You can do request.user.users.all()

    Note, this is unnecessarily confusing because of the related_name you've set, which defines the backwards relation from User to Event. Leave that out, and the code is more comprehensible:

    request.user.event_set.all()
    

    (If you must set one, at least call it events, not users.)