Take a look at something like django-selectreverse [1] for inspiration on how to reduce your querycount for M2M relations.
Koen [1] http://code.google.com/p/django-selectreverse/ On 17 mrt, 18:55, TheIvIaxx <theivi...@gmail.com> wrote: > I made a mistake in my model definitions above. The Term field on > Image is a ManyToMany() not ForeignKey(). > > Anyhow I did look into value_list, however it didn't add much, if any, > performance gain. But the select_related did! That was exactly what > I needed. Thanks Bruno for the tip. > > On Mar 17, 1:38 am, bruno desthuilliers > > <bruno.desthuilli...@gmail.com> wrote: > > On Mar 17, 4:24 am, TheIvIaxx <theivi...@gmail.com> wrote: > > > > Hello all, i have a question about a certain query i have. Here is my > > > model setup: > > > > class Term(): > > > term = CharField() > > > > class Image(): > > > image = FileField() > > > terms = ForeignKey(Term) > > > > These have been abbreviated for simiplicity, ut you get the gist of > > > it. Anyhow i have to query for a few hundred Image objects, then get > > > a list of Term objects for each of these. Really i just need the IDs > > > of the Terms. Currently i have my query like this: > > > > images = Image.objects.all() > > > you can use 'select_related' here - it'll use a join to prefetch > > related Term objects: > > > images = Image.objects.select_related('terms').all() > > > > responseImages = [] > > > for i in images: > > > terms = [term.id for term in n.terms.all()] > > > responseObjects.append({'image': n, 'terms': terms}) > > > I guess this is not your real code !-) > > > I don't know what this 'responseObjects' is - , but if you use Django > > templates, you just don't need all this above code. Just pass 'images' > > in the template's context and you'll be fine: > > > <ul> > > {% for image in images %} > > <li> > > <h3>{{ image.title }}</h3> > > <ul class="terms"> > > {% for term in image.terms.all %} > > <li>{{ term.id }}</li> > > {% endfor %} > > </ul> > > </li> > > {% endfor %} > > </ul> > > > HTH -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@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.