Sindre Sorhus
Sindre Sorhus

Reputation: 63478

Queryset from a ManyToMany relation

I'm creating a little calendar app in Django. I have two model classes; Calendar and Event. An event can be in multiple calendars. Because of this I'm using a ManyToMany relation.

This is my model

from django.db import models

class Calendar(models.Model):
    title = models.CharField(max_length = 255)

    def __unicode__(self):
        return self.title

class Event(models.Model):
    title = models.CharField(max_length = 255)
    start_date = models.DateField()
    end_date = models.DateField(blank = True, null = True)
    location = models.CharField(blank = True, max_length = 255)
    description = models.TextField(blank = True)
    important = models.BooleanField(default = False)
    calendar = models.ManyToManyField(Calendar)

How can I get a queryset with all events from a specific calendar?

Upvotes: 1

Views: 1451

Answers (3)

Tim
Tim

Reputation: 346

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

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599470

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)

Upvotes: 1

canisrufus
canisrufus

Reputation: 693

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

Upvotes: 0

Related Questions