简体   繁体   English

Django通过集合查询

[英]Django querying through sets

I'm new to Django and I'm stuck at querying through multiple sets. 我是Django的新手,但我坚持要查询多个集合。

I have three models; 我有三种模式;

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

Now I want a returned object set with only the projects that have appointments within a particular year. 现在,我想要一个返回的对象集,其中只包含在特定年份内具有约会的项目。 And that the appointment set objects in the project object contains only the ones in that year! 而且项目对象中的约会集对象仅包含该年的对象!

Is this easy to do with a django query or must i loop through the projects one by one and check all the appointments on the date? 使用django查询很容易做到吗?还是我必须一个接一个地遍历项目并检查日期中的所有约会?

I'm guessing that the appointment model is some how related to your projects and you just left that off. 我猜想约会模型在某种程度上与您的项目相关,而您只是忽略了这一点。

You probably want to use range and lookups that span relationships : 您可能要使用lookups that span relationships 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))

尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM