I am in Python 2.7 and Django 1.7.1 with django-restframework I have an API that returns me some specific values ββtaken from a database, it uses a custom serializer as follows:
class InventarioSerializer(serializers.ModelSerializer): item = serializers.RelatedField(source='producto.item') ubicacion = serializers.RelatedField(source='ubicacion.nombre') class Meta: model = Inventario fields = ('epc','item','cantidad','ubicacion')
My API is called like this:
class ItemEnInventarioViewSet(InventarioListModelMixin, viewsets.ModelViewSet): serializer_class = InventarioSerializer renderer_classes = (UnicodeJSONRenderer,)
and my ListModelMixin:
class InventarioListModelMixin(object): def list(self, request, *args, **kwargs): item = request.QUERY_PARAMS.get('item', None) inventario = Inventario.objects.filter(producto__item = item) if inventario.count() == 0: return HttpResponse(u"El item %s no se encuentra en el inventario" % item,status=400) self.object_list = inventario
It works fine, but when I try to create a database of about 1000 or more records, the serializer makes it very slow, arround from 25 to 35 seconds.
The query in the database is very simple, so the database is not a problem at all.
If I serialize a query with this function " data = serializers.serialize('json', myQuerySet) ", it takes no more than 3 seconds, but I donβt get the information on my own, so I use Custom Serializer
Is there a quickest way to get so many values? Maybe with another Serializer? any idea?
** ANSWER Thanks to Kevin ** Change request:
inventario = Inventario.objects.select_related('producto__item','ubicacion__nombre').filter(producto__item = item)
... forces the Serializer not to hit the database every row of results to get external values.