简体   繁体   中英

How to use serializer in Django REST Framework

I'm really new at Django REST framework. It's a very noob question but I'm not able to understand how does a serializer work? How do we send data to the serializer and how do we get data from it.
I'm trying to serialize my queryset as a list of dictionaries.
Here is my views.py :

def get(self,request):
    z= int(request.GET.get('q',''))
    queryset=[]
    queryset.append(models.Cart.objects.filter(UserId=z).values('id'))
    k=[]
    for values in queryset:
        k.append(models.ProductsDiscription.objects.filter(id=values).values())
    abc = serializers.NewSerializer(k,many=True)
    return JsonResponse({'pcartlist':((abc))})

If I don't use a serializer I get an error:

k:queryset is not json serializable.

So I tried to create a serializer, however I'm still getting the same error. I don't have any idea how to work with serializer.

serializers.py

class NewSerializer(serializers.Serializer):
    product_id= serializers.IntegerField()

k is the list of dictionries and i also dont know which field to use for that.

I have tried reading and understanding from every possible place but I'm unable to understand how serializers work. Please help me, if possible by giving a very simple example. It will be very helpful.

Please pass a queryset directly to a serializer. If you want to serialize a model, you can use a modelSerializer . A model serializer also needs a model name as a META attribute. The documentation can be found here

To serialize a queryset:

qs = YourModel.objects.all()
serializer = YourSerializer(qs, many=True)

The result after serialization can be obtained from serializer.data . You can do print (serializer.data) to see the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM