我想在返回的列表中添加id字段,它是每个对象的主键。
在我的models.py中:
class Category(models.Model):
name = models.CharField(max_length=200)
在我的serializers.py中:
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')
在我的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
)
我收到以下回复:
我想只添加id字段来获得此响应:
答案 0 :(得分:2)
只允许视图执行工作。
class Node {
String value;
Node left, right;
Node(String item) {
value = item;
left = right = null;
}
boolean isLeaf() {
return (left == null) && (right == null);
}
}