I am using Django REST framework for my API and I start using filters, depending on the value, it make various count, but it take at least 3 minutes everytime I make a response.
The serealizer use the context['request'] to get the url parameter and filter for the result
class CheetosSerializer(serializers.ModelSerializer):
total_cheetos = serializers.SerializerMethodField()
cheetos_on_sale = serializers.SerializerMethodField()
cheetos_on_stock = serializers.SerializerMethodField()
class Meta:
model = Cheetos
fields = (
'total_cheetos'
,'cheetos_on_sale'
,'cheetos_on_stock'
)
read_only_fields = fields
def get_total_cheetos(self,obj):
request_object = self.context['request']
customer_id = request_object.query_params.get('Shop__id_Cat_Customer')
if customer_id is None:
return Cheetos.objects.filter(Estatus=3).count()
else:
return Cheetos.objects.filter(Estatus=3,Shop__id_Cat_Customer = customer_id).count()
def get_cheetos_on_sale(self,obj):
request_object = self.context['request']
customer_id = request_object.query_params.get('Shop__id_Cat_Customer')
if customer_id is None:
return Cheetos.objects.filter(Estatus=3, id_Cat = 1).count()
else:
return Cheetos.objects.filter(Estatus=3, id_Cat = 1,Shop__id_Cat_Customer = customer_id).count()
def get_cheetos_on_stock(self,obj):
request_object = self.context['request']
customer_id = request_object.query_params.get('Shop__id_Cat_Customer')
if customer_id is None:
return Cheetos.objects.filter(Estatus=3, id_Cat = 2).count()
else:
return Cheetos.objects.filter(Estatus=3, id_Cat = 2,Shop__id_Cat_Customer = customer_id).count()
On the view is where I set the filterset parameter
class CheetosView(DefaultViewSetMixin):
filterset_fields = ['Shop__id_Cat_Customer']
queryset = Cheetos.objects.all()
serializer_class = CheetosSerializer
And I use postman to validate the data, and here it says the time it takes with the correct values I´m looking for: Postman Result
Is there a way to make this much better?