来自ManyToMany关系的Queryset

时间:2011-02-08 19:10:49

标签: python django django-models many-to-many

我正在Django中创建一个小日历应用程序。我有两个模型类;日历和活动。事件可以在多个日历中。因此,我使用的是ManyToMany关系。

这是我的模特

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)

如何获取包含特定日历中所有事件的查询集?

3 个答案:

答案 0 :(得分:1)

Django自动提供了一种访问ManyToMany关系中相关对象的方法:

events = my_calendar.events.all()

请参阅many-to-many relationships上的文档。

如果您还没有日历实例,只有一个ID或名称,您可以在一个查询中完成所有操作:

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

答案 1 :(得分:1)

您可以在Calendar记录的实例上使用.event_set属性。像这样:

# 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(标题= '2')。event_set.all()

答案 2 :(得分:0)

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

events = mycalendar.event_set.all()

采取并修改自:http://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships