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 proj开发者_开发知识库ects 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))
Try this
AppointmentGroup.objects.filter(appoinment_set__start_date__year=2011, appoinment_set__end_date__year=2011)
精彩评论