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

NoReverseMatch in django-machina, if forum's title contains Unicode characters
django rest framework - filter list of objects by filtering a list of objects
problema with django user
How to implement dictionary-like field in Django model?
Multiple Database in Django
Eztables Table Will Not Display
Django custom user model: initial migration depends on migration for default auth app
Django 1.7.1 dumpdata progress bar
Django - get Foreign Key first object in template
i want to fetch all data which is in my timeline but it is returning either first or last. DjangoRestMultipleModels
How to model a Many-to-many relation when the target model is a tuple in django?
Missing CSRF token when hitting password_reset endpoint
command cl.exe failed upon pip install django_compressor
Django view not returning what I want
How to change the table on admin site?
Why isn't django development server finding my static files

Categories

HOME
gdb
ng-idle
carousel
pearson-correlation
opengl-3
nstableheaderview
syntaxnet
pcl-crypto
android-securityexception
project-intu
activecollab
intercom
pybossa
altera
mvc-mini-profiler
selinux
simpleitk
php-mysqlidb
epsilon
tiki-wiki
pic32
paperjs
paragraph
jbutton
hibernate-validator
contacts
getpixel
batching
swagger-php
google-earth-engine
nohup
ods
c9.io
resolution
doc
postgresql-8.4
globalize
geotiff
wpas
skin
arules
quicktime
type-theory
javafx-css
node-request
xcode-server
spring-cloud-feign
mta
nikeplus-api
jboss-tools
refinerycms
clipboard.js
swizzling
shopping
bizagi
project-organization
fiware-monitoring
intel-c++
rpart
mod-proxy
dulwich
telepat
phpldapadmin
java-security
variadic-templates
uncaught-typeerror
primitive-types
cocos3d
buffering
renderer
twitter-bootstrap-rails
gae-quotas
ecslidingviewcontroller
beaker-testing
cnf
workitem
apache-abdera
iboutlet
lambdaj
jdb
gobject-introspection
fsevents
umra
uipagecontrol
msr
mtu
qglwidget
silent
application-verifier
nstokenfield
burndowncharts
fail-fast-fail-early
sqlobject
flvplayback
cardspace

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