Django通过集查询

时间:2011-04-08 08:00:03

标签: django objectset

我是Django的新手,我一直坚持通过多组查询。

我有三个型号;

class Project(models.Model):
    name = models.CharField(max_length = 100)

class AppointmentGroup(models.Model):
    name = models.CharField(max_length = 100) # not used in design.. delete when not used at the end of the project
    project = models.ForeignKey(Project)
    location = models.ForeignKey(Location)

class Appointment(models.Model):
    appointment_group = models.ForeignKey(AppointmentGroup)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

现在我想要一个返回的对象集,其中只包含在特定年份内具有约会的项目。并且项目对象中的约会集对象仅包含那一年的对象!

使用django查询是否容易,或者我必须逐个遍历项目并检查日期的所有约会?

2 个答案:

答案 0 :(得分:1)

我猜这个约会模型与你的项目有多大关系,你只是把它关了。

您可能想要使用rangelookups that span relationships

import datetime
start = datetime.date(2010, 1, 1)
end = datetime.date(2010, 12, 31)
projects_in_2010 = Projects.objects.filter(appointmentgroup__appointment__start_date__range(start, end))

答案 1 :(得分:0)

试试这个

AppointmentGroup.objects.filter(appoinment_set__start_date__year=2011, appoinment_set__end_date__year=2011)