简体   繁体   English

在 django 序列化程序 class 中仅序列化查询集中的某些字段

[英]serializing only certain fields from a queryset in django serializer class

I have a queryset which I obtain from get_queryset() .我有一个从get_queryset()获得的查询集。 What we know is, the returns of queryset gives the list of objects which contains all the fields of the model.我们知道的是,queryset 的返回给出了包含 model 的所有字段的对象列表。 Now I don't want to serialize all the fields from the model and show all of them in the response.现在我不想序列化 model 中的所有字段并在响应中显示所有字段。 I want to serialize only few fields and show in the api response.我只想序列化几个字段并在 api 响应中显示。

for eg:例如:

def get_queryset(self):

    """""
        filtering happens here on the query parameters.
    """
    abc = self.request.GET.get('abc',None)

Now I have a defualt list function where I have to call serializer class only with the specific fields.现在我有一个默认列表 function ,我必须在其中仅使用特定字段调用序列化程序 class 。

def list(self, request, *args, **kwargs):
    
    queryset = self.get_queryset()
    # data ={
    #     "name":queryset.
    # }
    
    # serializer = ExampleSerializer(data,many=True)
    #serializer = serializers.serialize("json",queryset=queryset,fields=['id','name','address'])        
    return Response(serializer, status=status.HTTP_200_OK)

When I do print queryset it gives complex queryset and when I do print(type(queryset)) ,it gives the following当我打印查询集时,它给出了复杂的查询集,当我print(type(queryset))时,它给出了以下内容

<class 'django.db.models.query.QuerySet'>

Now how to serialize name and address fields only to the exampleserializer class??现在如何仅将名称和地址字段序列化到示例序列化器 class? I did some digging and tried to do the following我做了一些挖掘并尝试执行以下操作

#serializer = serializers.serialize("json",queryset=queryset,fields=['id','name','address'])

but it does not give the output in the required format not like regular json.但它不像常规 json 那样提供所需格式的 output。 Also it gives model: Example in the response of every object.它还给出了 model:每个 object 响应中的示例。

Did you try this?你试过这个吗?

queryset = self.get_queryset().values('name', 'address')

I'm not sure I fully understand what you are trying to fetch as your code is incomplete, but it seems that what you need is a ModelSerializer .我不确定我是否完全理解您要获取的内容,因为您的代码不完整,但似乎您需要的是ModelSerializer
get_queryset() should be used to retrieve a queryset of objects that will be used by the serializer thanks to DRF inheritance & mixins system:由于 DRF inheritance 和 mixins 系统, get_queryset()应该用于检索序列化程序将使用的对象查询集:

# Serializer
class ExampleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Example
        fields = ('id', 'name', 'address')

# View
class ExampleList(ListAPIView):
    serializer_class = ExampleSerializer

    def get_queryset(self):
        return Example.objects.filter(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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