Without knowing too much about your code, the only thing I can say, having had a similar issue, was that select_related witha specified depth generally made for more efficient queries.
For fun, I started on some code to output database queries on all my pages while I'm debugging: <div id="django_debug"> <h2>Queries</h2> <p> {{ sql_queries|length }} Quer{{ sql_queries|pluralize:"y,ies" }} {% ifnotequal sql_queries|length 0 %} (<span style="cursor: pointer;" onclick="var s=document.getElementById ('debugQueryTable').style;s.display=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</ span>) {% endifnotequal %} </p> <ol id="debugQueryTable" style="display: none;"> {% for query in sql_queries %} <li class="{% cycle odd,even %}">{{ query.sql|wordwrap:40 }} ({{ query.time }})</li> {% endfor %} </ol> </div> I wrote this code when I was going through my site and making my queries more efficient. Another strategy that worked for me, is having an *ideal* SQL query and then trying to fit that into the Django way of grabbing objects. I already knew the most efficient query to use, so I had to just hack around until Django did what I want. Hope this helps. On Dec 6, 8:56 pm, erikcw <[EMAIL PROTECTED]> wrote: > Hi all, > > I'm trying to write a model query that will return a queryset along > with the latest (and earliest) data from 2 related models. > > Right now I'm doing something like this: > > objects = Model1.objects.filter(user=3).select_related() #about 6,000 > objects > > data = {} > for o in objects: > data[o.name] = [o.field1, o.field2] > data[o.name].append(o.field3.model2_set.all().latest('created')) > #get latest row from related model2 > data[o.name].append(o.model3_set.all().order_by('created')[0]) > #get earliest row from related model3 > > The problem is that this results in a TON of database queries. This > view is taking over a minute to process. The select_related on the > first line doesn't seem to be helping since I'm using latest()/ > order_by which generates a new query. > > How can I make this more efficient? Denormalizing the isn't an option > since model2 and model 3 are many-to-one. > > Is there something I can do with extra() in the first query or some > sort of subquey I can do to eliminate the loop? > > Thanks! > Erik --~--~---------~--~----~------------~-------~--~----~ 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 [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---