select_related
tumb1er opened this issue · comments
Sergey Tikhonov commented
I.e., we have City-Country-Continent db schema. I need to obtain continents for some cities. To do this, now I have these options:
- query City with depth=2
- write custom serializer class on server side
depth
is not a bad option, but if you need more than one join, all these relations may become a problem.
So, the proposal is to add "select_related" option to filter()
arguments.
- it adds
qs.select_related(*fields)
to serializers queryset - it automatically created fields, named like
select_related
values
For example:
>>> client.filter('City', kwargs={
'filters': {},
'select_related': ['country__continent']
})
[{
'id': 1,
'name': 'Moscow',
'country__continent': 'Eurasia'
}]
Problems found:
- Django
select_related()
adds related objects asobj.country.continent
- Thus, you need to write complex serializer method to obtain continent serialized data
- if you setattr this method to
GenericSerializerClass
object, it doesn't become 'bound method', so some__new__
magic is needed - also,
ModelSerializer
need to be constructed forContinent
model, and model class must be resolved before instantiation ofGenericSerializerClass
Lot's of stuff to think about.
Alexey Manaev commented
Thanks!