How to serialize Django queryset.values() into json?

前端 未结 5 398
情话喂你
情话喂你 2020-12-13 13:31

I have a model that has many fields, however for this problem I only need 3 of those fields. When I try to serialize a .values set I get an exception:

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 14:17

    Django serializers can only serialize queryset, values() does not return queryset rather ValuesQuerySet object. So, avoid using values(). Rather, specifiy the fields you wish to use in values(), in the serialize method as follows:

    Look at this SO question for example

    objectQuerySet = ConventionCard.objects.filter(ownerUser = user)
    data = serializers.serialize('json', list(objectQuerySet), fields=('fileName','id'))
    

    Instead of using objectQuerySet.values('fileName','id'), specify those fields using the fields parameter of serializers.serialize() as shown above.

提交回复
热议问题