Answer the question
In order to leave comments, you need to log in
How to turn QuerySet into JSON?
there is this code:
def post(self, request):
fields = ["en_mm", "height", "diametr", "season", "cartype"]
qs = TireModel.objects.all()
for field in fields:
if request.POST.get(field) != "" and request.POST.get(field) != "All":
qs = qs.filter(**{field: request.POST.get(field)})
print(qs) # Выводит <QuerySet []>
return JsonResponse({"data": "1"}, status=200)
Answer the question
In order to leave comments, you need to log in
1. What you really need is not JSON, but a dictionary. Do not confuse these things :) JSON is a string formatted in such a way that it is very similar to a Python dictionary. It is used not only in Python, but in many other places.
2. If you want to find an answer, then the word "serialize" (eng. "serialize") is useful for Google, this is about what you need.
Usually they use DRF for this, here is a serialization tutorial in it
. The result will be something like this:
from rest_framework import serializers
class TireSerializer(serializers.ModelSerializer):
class Meta:
model = Tire
fields = ["en_mm", "height", "diametr", "season", "cartype"]
def post(self, request):
fields = ["en_mm", "height", "diametr", "season", "cartype"]
qs = TireModel.objects.all()
for field in fields:
if request.POST.get(field) != "" and request.POST.get(field) != "All":
qs = qs.filter(**{field: request.POST.get(field)})
serializer = TireSerializer(qs, many=True)
print(serializer.data)
<QuerySet []>
, then the point is that the database is full: there simply wasn’t a single Tire to match all the applied filters. from rest_framework import serializers
def serialize_tires(tires):
return [
{"en_mm": tire.en_mm,
"height": tire.height,
"diametr": tire.diametr,
"season": tire.season,
"cartype": tire.cartype} for tire in tires]
def post(self, request):
fields = ["en_mm", "height", "diametr", "season", "cartype"]
qs = TireModel.objects.all()
for field in fields:
if request.POST.get(field) != "" and request.POST.get(field) != "All":
qs = qs.filter(**{field: request.POST.get(field)})
print(serialize_tires(tires))
use values_list for QuerySet
and then convert the result to JSON
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question