On Mon, Feb 23, 2009 at 12:40 PM, sphogan <spho...@gmail.com> wrote: > > I'm surprised that this hadn't come up for me before, but nonetheless, > here I am. > > My problem is that I want to get related items (in a similar situation > to getting blog articles with their comments) without looping a second > lookup (since it would be a couple thousand items and building a page > off a couple thousand queries isn't a good idea). > > Basically, the schema is like this: > > Article(models.Model): > #fields for article > > Comment(models.Model): > #fields for comment > article = models.ForeignKey(Article) > > Simple enough. If I wanted to get all the comments and their related > article, I could do: > > Comment.objects.select_related('article').all() > > However, select_related() only works on the object the foreign key is > declared on (http://docs.djangoproject.com/en/dev/ref/models/querysets/ > #id4 <http://docs.djangoproject.com/en/dev/ref/models/querysets/%0A#id4>; > specifically, "You can only refer to ForeignKey relations in the > list of fields passed to select_related.") Presumably this is because > it does an INNER JOIN rather than a LEFT OUTER JOIN and would > therefore miss articles with no comments. > > What I would like to be able to do is: > > Article.objects.select_related('comment_set').all() > > This seems like a somewhat simple case and there seems to be no > mention of it in the documentation anywhere. > > Sean. > > > > That's not possible, but that doesn't really affect anything, you still have that accessor available to you, but it does an extra SQL query, that is to say select_related does not affect the data avilable to you, it is a performance optimization.
Alex -- "I disapprove of what you say, but I will defend to the death your right to say it." --Voltaire "The people's good is the highest law."--Cicero --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---