与nullable字段有关的select_related在视图中无法正常工作

时间:2018-09-30 12:54:37

标签: python django unit-testing django-models django-select-related

我正在Django视图中使用select_nullable来检索可以为null的关系

  

必须指定可空外键

因此,我明确地将其作为参数传递:

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

问题是,当我在模板中访问它时,它会生成一个数据库查询,即:

# items/templates/items/source.html
{{source.language.code}}

使用以下方法进行测试:

    # 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)

生成:

...
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

涉及的模型定义为:

# 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)

enter image description here

如何使用select_related不在视图中生成数据库查询?

0 个答案:

没有答案