Monday, 15 June 2015

python - Django - source in serializers leading to too many database calls -



python - Django - source in serializers leading to too many database calls -

i trying create song-artist-album relationship in django. have next models:

class artist(models.model): gid = models.charfield(max_length=63, blank=true) name = models.charfield(max_length=255, blank=true) begin_life = models.charfield(max_length=31, blank=true) end_life = models.charfield(max_length=31, blank=true) type = models.charfield(max_length=1, blank=true) gender = models.charfield(max_length=1, blank=true) class song(models.model): gid = models.charfield(max_length=63, blank=true) title = models.charfield(max_length=255, blank=true) artist = models.foreignkey('artist', related_name='songs_artist') album = models.foreignkey('album', related_name='songs_album') length = models.integerfield(default=0)

i have created artistserializer can retrieve songs of artist when info of particular artist. serializer have created:

class artistserializer(serializers.modelserializer): songs_artist = songserializer(source='songs_artist') class meta: model = artist fields = ('name', 'type', 'gender', 'begin_life', 'end_life', 'songs_artist') class songserializer(serializers.modelserializer): artist = songartistserializer() album = songalbumserializer() class meta: model = song fields = ('id', 'title', 'artist', 'album', 'length') class songartistserializer(serializers.modelserializer): class meta: model = artist fields = ('id', 'name')

a quick profiling on method of artist revealed troubling facts. next results of profiling ordered time , number of calls: http://pastebin.com/bwcksn2i.

but, when removed songs_artist field serializer, next output of profiler: http://pastebin.com/0s5k4w7i.

if read right, database beingness nail 1240 times when utilize source!

is there other alternative doing this?

thanks in advance.

django rest framework not optimize queries you, it's decide how best remove n+1 queries. should follow guidelines covered in the django documentation handle performance issues.

in case of foreignkey relationships, should utilize select_related in query, pre-fetch objects in original query.

in case of manytomany , genericforeignkey relationships, should utilize prefetch_related. i've written quite bit in another stack overflow answer, gist utilize similar select_related.

you should override query in get_queryset on view best results, don't need worry django rest framework incorrectly cloning queryset when used attribute on class.

python django django-rest-framework

No comments:

Post a Comment