• Home
  • About me

Diego Búrigo Zacarão’s Weblog

Let me talk about something

Follow me
Twitter
Posts
Comments
« Toshio’s origami
Transifex 0.7 – Pyro is coming soon »

Django Generic Relation fields with get_object_or_404 shortcut

Jul 17th, 2009 by diegobz

Those days me and Ignacio were investigating a weird slowness in a feature of Transifex at http://transifex.net. For some reason there was a query that was taking so long to return the result and we were wondering why?

That was the query:

pofile = get_object_or_404(POFile, component=component, filename=filename)

This query intents to find a PO file with a specific name for a component. Component in this case, in the POFile model, is a generic relation that can be pointed to any object. It is not just a foreignkey to the Component model. Other models can be pointed there too.

The truth here is that, the POFile model does not have a ‘component’ field. It has two others fields instead, called ‘object_id’  and ‘content_type’. Django does a kind of magic and can discover that the ‘component’ field does exist and then relate it to the generic relation present in the model.

That’s really cool, but in the other hand it takes a lot of time. We got the same result using a more specific query and it brought a real gain of performance.

from django.contrib.contenttypes.models import ContentType
ctype = ContentType.objects.get_for_model(component)
pofile = get_object_or_404(POFile, object_id=component.pk, content_type=ctype, filename=filename)

Tags: Django, Transifex

Posted in Django, English, Fedora, Transifex

2 Responses to “Django Generic Relation fields with get_object_or_404 shortcut”

  1. on 18 Jul 2009 at 4:24 am1Christos Trochalakis

    Diego could you try this instead and see what happens (I don’t have a working tx instance):

    pofile = get_object_or_404(component.pofiles, filename=filename)

  2. on 18 Jul 2009 at 11:39 am2diegobz

    @Christos
    Good point. Looks like it works well too. :)

  • Recent Posts

    • Generic Python Decorators
    • FISL 12
    • Dear (Slovenian) Translator
    • Django Database Router using settings
    • Django reverse with JavaScript
    • Enabling apache UserDir (public_html) with SELinux enabled on Fedora
  • Twitter Updates

      more updates...
    • Translate this page

    • Categories

      • Django (8)
      • English (50)
      • Europe (18)
      • Event (6)
      • Fedora (49)
      • FISL (6)
      • FUDCon (5)
      • GSoC (11)
      • Indifex (2)
      • Mini-post (5)
      • Photos (12)
      • PHP (1)
      • Português (14)
      • Python (1)
      • SELinux (1)
      • Transifex (34)

    Diego Búrigo Zacarão’s Weblog © 2008-2012 All Rights Reserved.

    Cool WordPress Themes | WordPress Rocks!