简体   繁体   中英

Django querying through sets

I'm new to Django and I'm stuck at querying through multiple sets.

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?

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 :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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