如何防止在 Django 中对该字段进行额外查询?
How to prevent extra query for this field in Django?
我有这样的模型:
class City(models.Model):
some_field = models.ForeignKey('self')
name = models.CharField(max_length=100)
class Author(models.Model):
city = models.ForeignKey(City)
# other fields
def get_some_field(self):
return self.city.some_field
some_field = cached_property(get_some_field, name='some_field')
我获取 Author 查询集是这样的:
author_qs = Author.objects.filter(**some_filter).select_related('city')
现在获取查询集后,我会做这样的事情:
city_name = author_qs.some_field.name
但是这一行正在为城市模型再次查询数据库。我怎样才能防止这个额外的查询,并且只用以前的查询得到 city_name。
P.S。我不能直接得到author_qs.city.name
。我要求它仅从 some_field
调用
请尝试以下操作:
author_qs = Author.objects.filter(**some_filter).select_related('city__some_field')
我有这样的模型:
class City(models.Model):
some_field = models.ForeignKey('self')
name = models.CharField(max_length=100)
class Author(models.Model):
city = models.ForeignKey(City)
# other fields
def get_some_field(self):
return self.city.some_field
some_field = cached_property(get_some_field, name='some_field')
我获取 Author 查询集是这样的:
author_qs = Author.objects.filter(**some_filter).select_related('city')
现在获取查询集后,我会做这样的事情:
city_name = author_qs.some_field.name
但是这一行正在为城市模型再次查询数据库。我怎样才能防止这个额外的查询,并且只用以前的查询得到 city_name。
P.S。我不能直接得到author_qs.city.name
。我要求它仅从 some_field
请尝试以下操作:
author_qs = Author.objects.filter(**some_filter).select_related('city__some_field')