dimanche 30 septembre 2018

select_related on nullable fields does not work as expected in view

I am using select_nullable in a Django view to retrieve a relationship that can be null

nullable foreign keys must be specified

So I am explicitely passing it as a parameter:

source_text = get_object_or_404(Text.objects.select_related('language'), pk=source_text_pk) 

The problem is that when I'm accessing it in a template it generates a database query, i.e.:

# items/templates/items/source.html


Testing it with:

    # items/tests/test_views.py
    ...
    source_text = TextFactory()
    context = {'source': source_text}
    with self.assertNumQueries(0):
        # render the template with given context to trigger possible db hits
        from django.template.loader import render_to_string
        rendered = render_to_string("items/source.html", context)

Generates:

...
AssertionError: 1 != 0 : 1 queries executed, 0 expected
Captured queries were:
1. SELECT "languages_language"."id", "languages_language"."name", "languages_language"."code" FROM "languages_language" WHERE "languages_language"."id" = 16

Involved models are defined as:

# items/models.py
class Text(models.Model):
    language = models.ForeignKey('languages.Language', 
                             on_delete=models.SET_NULL,
                             blank=True,
                             null=True)
# languages/models.py
class Language(models.Model):
    name = models.CharField(max_length=200)
    code = models.CharField(max_length=35)
    def __str__(self):
       return "name: {} \tcode: {}".format(self.name, self.code)

How should I use select_related to not generate a database query in the view?

Aucun commentaire:

Enregistrer un commentaire