gpt4 book ai didi

python - 来自 ManyToMany 关系的查询集

转载 作者:行者123 更新时间:2023-12-01 06:12:39 26 4
gpt4 key购买 nike

我正在 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)

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

最佳答案

您可以在日历记录的实例上使用 .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(title='two').event_set.all()

关于python - 来自 ManyToMany 关系的查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4937226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com