【发布时间】:2021-07-17 13:19:18
【问题描述】:
models.py 文件,其中包含具有名称、描述 parent_category 字段的类别模型
class Category(models.Model):
""" Categories representation model """
name = models.CharField(max_length=50)
description = models.TextField()
parent_category = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
serializers.py 文件,该文件包含 Category 模型序列化器及其所有字段
class CategorySerializer(serializers.ModelSerializer):
""" product categories model serializer """
parent_category = CategorySerializer()
class Meta:
""" profile model serializer Meta class """
model = Category
fields = (
'id',
'name',
'description',
'parent_category'
)
views.py 文件,API 视图,通过所需的用户身份验证获取所有可用类别
class GetCategoriesView(APIView):
""" product categories getting view """
permission_classes = (IsAuthenticated,)
def get(self, request, *args, **kwargs):
""" get request method """
categories = Category.objects.all()
serializer = CategorySerializer(categories, many=True, context={'request':request})
return Response(data=serializer.data, status=HTTP_200_OK)
预期结果,来自 parent_category 字段的递归数据的 Json 结果
{
name:'boy shoes',
description:'boy shoes category description'
parent_category:{
name:'shoes',
description:'shoes category description',
parent_category:{
name:'clothes',
description:'clothes category description',
parent_category: null
}
}
}
我得到错误,我注意到我无法直接访问同一个类中的类
NameError: name 'CategorySerializer' is not defined
我该如何解决?,我想你可以帮助解决这个问题
感谢您的关注:)
【问题讨论】:
-
你能显示整个视图文件吗?
-
为什么
parent_category = CategorySerializer()类中有parent_category = CategorySerializer()行?由于描述中没有指定错误堆栈,我猜这就是错误发生的地方。 -
默认情况下,它只会呈现 parent_category 的 id,例如 {name:'category', description:'category description', parent_category:3},所以如果我想将其自定义为 json 我必须指定它 Serializer 类
标签: python json django django-rest-framework django-serializer