Django select related in raw request

后端 未结 3 1918

How to make \"manual\" select_related imitation to avoid undesirable DB hits?

we have:

class Country:
    name = CharField()
class City:
    country          


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 10:38

    A solution with prefetch_related (this means that two queries will be made, 1 for the cities and 1 for the countries) taken from django-users which is not part of the public API but is working on Django 1.7

    from django.db.models.query import prefetch_related_objects
    #raw querysets do not have len()
    #thats why we need to evaluate them to list
    cities = list(City.objects.raw("select * from city inner join country on city.country_id = country.id where name = 'london'"))
    prefetch_related_objects(cities, ['country'])
    

    UPDATE

    Now in Django 1.10 prefetch_related_objects is part of the public API.

提交回复
热议问题