On Mar 19, 8:20 pm, adrian <adrian...@gmail.com> wrote: > The doc gives this example for querying an Entry model which has a > foreign key field to a Blog model. > > e = Entry.objects.get(id=2) > e.blog = some_blog > > Fine. Now if I do it in a loop like this: > > e = Entry.objects.all() > for entry in e: > entry.blog = some_blog > #do stuff here with Entry and Blog > > My question is, would this create a lot of SQL statements? When does > Django query the > foreign key field? Does it get all the blog entries at once with the > Entry.objects.all() query, > or does it do it one by one in the loop? > > How would I do that efficiently because I need to create a single dict > from the value of my model and all its foreign key models, so that I > can serialize it for Ajax? > > Thanks
Yes, as written it would create an SQL statement for each Entry object. The solution - which is documented - is to use select_related when getting the entry options. This follows the relation and prepopulates the blog object: e = Entry.objects.select_related().all() See http://docs.djangoproject.com/en/dev/ref/models/querysets/#id4 By the way, if you're concerned about how many queries your ORM code is generating, you can use the tip here to see them: http://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running -- DR. --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---