Using `defer` or` only` on ForeignKey

I am trying to squeeze a few milliseconds from a view. I would like to avoid loading some fairly large text fields from a model ForeignKeythat I will not use.

To make it more understandable:

class Foo(models.Model):
    slug = models.SlugField()
    text1 = models.TextField()
    text2 = models.TextField()
    ...

    @models.permalink
    def get_absolute_url(self):
        return ('foo_detail', (), {"object_id": self.pk, "object_slug": self.slug})


class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    ...

Then in the template:

 {% for bar in bars %}
      {{ bar.foo.get_absolute_url }}
 {% endfor %}

Now, if you look at the requests issued ormom for each fooDjango retrieves each field (as expected), but in the end only the need pkand slug. In my case, this is more or less hundredths of a second per object on my test machine.

Of course, I could write a method like this:

class Bar(models.Model):
    ...
    def get_foo_absolute_url(self):
        return Foo.objects.only('pk', 'slug').get(pk=self.foo).get_absolute_url()

and use it in a template, but it's ugly as hell.

Has anyone come across the same problem and come up with a better solution?

+4
1

, - URL- memcache/state .

URL, models.permalink, .

0

All Articles