Thanks Kevin, you got me on the right track. I was able to implement the following solution:
records = models.Facility.objects.filter(...) for x in records: schedule = x.schedule_set.all() But I could not find a way to do it all at once like records = models.Facility.objects.filter(...).schedule_set.all() If there is not a "clean" method to do this, I'm inclined to use the above solution since I have only ~100 records in the first query. I don't want to "drop into SQL" unnecessarily. On this query, I probably only need the .count() method on schedule_set() if that even makes a difference. -----Original Message----- From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On Behalf Of Kevin Sent: Tuesday, October 11, 2011 8:43 AM To: Django users Subject: Re: Need advice on ForeignKey query problem. What your looking for is here in the documentation: https://docs.djangoproject.com/en/1.3/topics/db/queries/#related-objects records = models.Facility.objects.get(pk=62).schedule_set.all() On Oct 10, 8:19 pm, "Sells, Fred" <fred.se...@adventistcare.org> wrote: > I've got these two tables defined where a Facility can have multiple > schedules but a schedule can have only one facility. > > class Facility(models.Model): > id = models.CharField(max_length=2, primary_key=True) > name = models.CharField(max_length=30) > .... > > class Schedule(models.Model): > facility = models.ForeignKey(Facility) > ... > > I would like a query that returns one record for each Facility and that > record would contain at least the id (if not more) of ALL linked > schedules. So far I've only been able to return a queryset that > contains a record for each schedule at each facility. My last attempt > looked like this... > > records = models.Facility.objects.select_related().filter(id='62') > > is there a pythonic way to do this? I only need reasonable efficiency, > there's not that much data and the query is probably only run 200 times > in an 8 hour shift. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.