简体   繁体   English

将主键添加到序列化器

[英]Adding the primary key to the serializer

I want to add the id field, which is the primary key to each object, in the list I'm returning 我想在返回的列表中添加id字段,它是每个对象的主键

in my models.py: 在我的models.py中:

class Category(models.Model):
     name = models.CharField(max_length=200)

in my serializers.py: 在我的serializers.py中:

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'name')

in my views.py: 在我的views.py中:

class ListCategoriesView(generics.ListAPIView):
"""
Provides a get method handler.
"""

serializer_class = CategorySerializer


def get(self, request, *args, **kwargs):
    token = request.META.get("HTTP_TOKEN","")
    if not token:

        """ do some action here """

    if not UserAccess.objects.filter(accessToken=token).exists():

        """ do some action here """

    else:
        serialized_categories = []
        all_categories = Category.objects.all()
        for category in all_categories:
          """ I'm filling the object here with the id , and the name """
            serialized_item = CategorySerializer(data={
                    "id": category.id,
                    "name": category.name
                })
            if serialized_item.is_valid():
                serialized_categories.append(serialized_item.data)
        return Response(
            data=serialized_categories,
            status=status.HTTP_200_OK
        )

I'm getting the below reponse : 我收到以下回复:

在此处输入图片说明

I want to get this response just with the id field added: 我想只添加id字段来获得此响应:

在此处输入图片说明

Just allow the view to do the work. 只需让视图完成工作即可。

class ListCategoriesView(generics.ListAPIView):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()

    def list(self, request, *args, **kwargs)
        token = request.META.get("HTTP_TOKEN","")
        if not token:
            """ do some action here """
        elif not UserAccess.objects.filter(accessToken=token).exists():
            """ do some action here """
        else:
            return super().list(request, *args, **kwargs)

暂无
暂无

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

相关问题 Serializer 上的 SerializerClass 字段从主键保存 - SerializerClass field on Serializer save from primary key 将外键数据添加到序列化程序? - Adding foreign key data to serializer? Django Rest Framework:访问serializer.is_valid -> serializer.errors 中字段的主键 - Django Rest Framework : Access primary key of field in serializer.is_valid -> serializer.errors 在Alembic中向现有MySQL表添加主键 - Adding primary key to existing MySQL table in alembic 在序列化程序中使用非主键验证外键字段 django rest 框架 - Validating a foreign key field with non-Primary Key in a serializer django rest framework 修复 Django Rest 框架 Model 序列化程序相关主键查询集中的错误 - Fixing Error in Django Rest Framework Model Serializer Related Primary Key Queryset Django REST Framework:如何向使用直通表的 M2M 序列化程序添加外主键? - Django REST Framework: How to add a foreign primary key to an M2M serializer that uses a through table? Django Rest Framework:验证序列化程序时如何忽略“唯一”主键约束? - Django Rest Framework: How to ignore 'unique' primary key constraint when validating a serializer? Django Rest Framework在POST中接收主键值并将模型对象作为嵌套序列化器返回 - Django Rest Framework receive primary key value in POST and return model object as nested serializer 如何通过添加新的主键字段在Django中更新模型? - how to update model in django by adding new primary key field?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM