[Answered ]-Queryset from a ManyToMany relation

1πŸ‘

βœ…

You would use the .event_set attribute on an instance of a Calendar record. Like this:

# create two calendars
one = models.Calendar.objects.create(title='calendar one')
two = models.Calendar.objects.create(title='calendar two')

# attach event 1 to both calendars
event = models.Event.objects.create(title='event 1', start_date='2011-11-11')
one.event_set.add(event)
two.event_set.add(event)

# attach event 2 to calendar 2
two.event_set.add(models.Event.objects.create(title='event 2', start_date='2011-11-11'))

# get and print all events from calendar one
events_one = models.Calendar.objects.get(title='calendar one').event_set.all()
print [ event.title for event in events_one ] 
# will print: [u'event 1']

# get and print all events from calendar two
events_two = models.Calendar.objects.get(title='calendar two').event_set.all()
print [ event.title for event in events_two ] 
# will print: [u'event 1', u'event 2']

models.Calendar.objects.get(title=’two’).event_set.all()

πŸ‘€Tim

1πŸ‘

Django automatically provides a way to access the related objects in a ManyToMany relationship:

events = my_calendar.events.all()

See the docs on many-to-many relationships.

If you don’t already have a calendar instance, but just an ID or name, you can do the whole thing in one query:

events = Event.objects.filter(calendar__id=my_id)

0πŸ‘

mycalendar = Calendar.objects.get(id=1)

events = mycalendar.event_set.all()

Taken and modified from: http://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships

πŸ‘€canisrufus

Leave a comment