[英]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.