0

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?

worm2d
  • 159
  • 1
  • 2
  • 14

1 Answers1

1

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.)

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • don't know how you expand `request.user` since op didn't provide info about request.user – Avinash Raj Mar 18 '16 at 09:08
  • 1
    Why would OP need to provide any information? `request.user` is provided by Django; even if they substituted their own model, that makes no difference to the fact that we are interested in the *reverse* relation, which is defined on Event. – Daniel Roseman Mar 18 '16 at 09:21
  • What is the content of the intermediate table? Do the events have different user_ids? – Daniel Roseman Mar 18 '16 at 09:40
  • @Daniel Roseman can you please also help me with another one thing - now i need to output all event information from Event model, where `event_id` from that additional table is equal to some variable `foo` – worm2d Mar 18 '16 at 10:30
  • You're thinking about these things the wrong way; don't worry about "additional tables", try to formulate your problem in terms of the Django classes you have. But if you can't solve this, please ask a new question. – Daniel Roseman Mar 18 '16 at 10:32