NameError: name 'Class' is not defined,如何在 Django 中访问同名的类?

时间:2021-04-23 10:17:28

标签: python json django django-rest-framework django-serializer

models.py 文件,包含带有名称、描述 parent_category 字段的 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

    

我该如何解决?,我想你可以帮助解决这个问题

<块引用>

感谢您的关注:)

1 个答案:

答案 0 :(得分:1)

您不能使用与类变量相同的类。仅供参考

class SomeClass:
    x = SomeClass() # won't work NameError: name 'SomeClass' is not defined
    
    def __init__(self):
        x = SomeClass() # this is OK

所以你必须把你的序列化器改成这样

class CategorySerializer(serializers.ModelSerializer):
    """ product categories model serializer """

    class Meta:
        """ profile model serializer Meta class """
        model = Category
        fields = (
            'id',
            'name',
            'description',
            'parent_category'
        )

    def get_fields(self):
        fields = super().get_fields()
        fields['parent_category'] = CategorySerializer()
        return fields