django


Give a ModelSerializer, can I get related model fields used for QuerySet.only?


I found my drf view is too slow due to Fat SQL SELECT Clause from DB.
So I want to select columns only required by bound serializer, thus I can write my view class like this:
class ProductSerializer(serializers.ModelSerializer):
company_id = serializers.IntegerField(source='company_id')
company_name = serializers.serializers.CharField(source='company.name')
class Meta:
fields = (
'id', 'name', 'company_id', 'company_name'
)
class ListRetrieveProductViewSet(UpdateNonExistentMixin, viewsets.ReadOnlyModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
def get_queryset(self):
return self.queryset.select_related(
'company'
).only(*self.serializer_class.get_model_field_names())
self.serializer_class.get_model_field_names() may result ['id', 'name', 'company_id', 'company__name'].
How to implement get_model_field_names or is there any existing implementations?
I'll give this another go. There is no automatic way (barring 3rd party packages) to do the company_name to company__name conversion. What you can do is create another variable under Meta:
class Meta:
fields = (
'id', 'name', 'company_id', 'company_name'
)
fields_for_query = (
'id', 'name', 'company_id', 'company__name'
)
then fetch it like so:
list(self.get_serializer_class().Meta.fields_for_query)
This approach makes it a bit more manageable since they're beside each other. Typically, you'd turn the fetch method into a mixin like so:
class FieldForQueryMixin(object):
def get_field_for_query(self):
assert hasattr(self.get_serializer_class().Meta, 'fields_for_query'), 'Serializer Meta is missing fields_for_query field yo.'
return list(self.get_serializer_class().Meta.fields_for_query)
# use like so
class ListRetrieveProductViewSet(UpdateNonExistentMixin, FieldForQueryMixin, viewsets.ReadOnlyModelViewSet):
pass

Related Links

Changing base template based on request.user in Django
django- how to check validity of single input field inside multi input form
Django-nonrel can't login as super user
Django: Adding Permission to an Specific Model Instance
Django + AppEngine counting more the 1000 records
django import a view function
Multiple Django apps hitting same backing DB - Issues?
Django - How to access the verbose_name of a Model in its Admin Module?
CSV only taking first record
Is it possible to pass query parameters via Django's {% url %} template tag?
TemplateSyntaxError NoReverseMatch when adding a page to Django-page-cms
Django add empty field on forms
Django - How do I redirect ie6?
Django url image extraction like facebook
Displaying a many-to-many fields
Customize the django User management

Categories

HOME
batch-file
grok
fabricjs
polymer
c99
jax-rs
rendering
ms-access-2016
onclick
python-multithreading
code-coverage
heap
enterprise-architect
libusb
glyphicons
digital-signature
named-entity-recognition
ios10.2
exploit
monit
inversion-of-control
magento-1.8
custom-controls
paragraph
turfjs
erb
autolisp
android-sugarorm
instantiation
vue-chartjs
yowsup
video-capture
sim-card
wc
httr
optimizely
vaadin-elements
spring-integration-sftp
rserve
context-switch
stdmap
dt
template-toolkit
android-instrumentation
visual-studio-2008-sp1
pure-css
envi
dotnetnuke-7
lean
http-status-code-401
nss
gcloud-ruby
aspen
concept-insights
atan2
viola-jones
rdflib
botan
openbabel
android-cookiemanager
mruby
webfinger
raygun
lambda-architecture
functional-java
qscrollarea
gtm-oauth2
mongohq
observium
joomla3.1
qi4j
jquery-blockui
subproject
denied
htdocs
socketserver
diagrams
delimited-text
silent
folding
spread
lxr
build-environment
wordprocessingml
scrubyt
httpcookie

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App