KristianOellegaard/django-hvad — Issue #28: How to include translated model when using select_related?
Author: bradenmacdonald
Created: 2012-03-06 04:57:19+00:00
State: open

I'm trying to use `select_related` on some translated models in order to reduce the number of queries needed when loading a page on my site.

I was able to get `select_related` working (see mstarinc/django-hvad@cf66fec33038162b26a6d3cc92a7dabcd3f690df ), but it only selects the shared model across relationships, and doesn't include related translated models. So when I later try to access translated fields across a relation, it generates a new query for each object.

Would someone mind commenting on my commit and giving me some guidance as to what I will have to change to get this fully working?

Here's the setup I have:

```
class Location(TranslatableModel):
""" A location (e.g. a venue where an event is held. """
city = models.CharField(max_length=30, blank=True)
country = models.CharField(max_length=2, blank=True, choices=common_fields.COUNTRY_CHOICES)

translations = TranslatedFields(
name = models.CharField(max_length=128, blank=True),
)

class Event(TranslatableModel):
event_type = models.ForeignKey(EventType, blank=True, null=True)
date = models.DateField()
location = models.ForeignKey(Location, blank=True, null=True)

translations = TranslatedFields(
name = models.CharField(max_length=128),
description = models.TextField(blank=True, null=True),
)
```

What I want to do is

```
all_events = Event.objects.language().select_related('event_type', 'location').all()
```

After I modified django-hvad, the above query works fine and properly retrieves the related objects, but the `Location` objects are untranslated, so if I do something like `[e.location.name for e in all_events]`, it generates an extra query for every `Event` object. If I access 'location.name' using `safe_translation_getter`, it returns `None`, and if I use `lazy_translation_getter`, it generates 3 queries per `Event` object, which is even worse (2 existence queries, and one to get the name).