gpt4 book ai didi

django - FieldError at/Related Field 得到无效查找 : is_null

转载 作者:行者123 更新时间:2023-12-04 08:35:12 24 4
gpt4 key购买 nike

我正在创建一个评论 api 但当我运行服务器时出现此错误:

FieldError 在/相关字段得到无效查找:is_null

我不知道怎么解决。我正在创建一个嵌套的评论 api。这是我的代码:

#序列化器

class CommentSerializer(serializers.ModelSerializer):
loadParent = serializers.SerializerMethodField("loadPrentData")

def loadPrentData(self, comment):
comments = Comment.objects.filter(parent=comment)
comments_ser = CommentSerializer(comments, many=True).data
return comments_ser

class Meta:
model = Comment
fields = ['id', 'user', 'product', 'parent', 'body', 'created', 'loadParent']


class ProductSerializer(serializers.ModelSerializer):
comments = serializers.SerializerMethodField("loadProductComments")

def loadProductComments(self, _product):
_comments = Comment.objects.filter(product=_product, parent__is_null=True)
_comments_ser = CommentSerializer(_comments, many=True, read_only=True).data
return _comments_ser

class Meta:
model = Product
fields = ['id', 'category', 'name', 'slug', 'image_1',
'image_2', 'image_3', 'image_4', 'image_5',
'description', 'price', 'available', 'created', 'updated', 'comments']
lookup_field = 'slug'
extra_kwargs = {
'url': {'lookup_field': 'slug'}
}

#views:

@api_view()
def AddComent(request, parent_id=None):
parent = request.data.get("parent_id")
serializer = CommentSerializer(data=request.data)
if serializer.is_valid():
if parent is not None:
comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'],
parent_id=serializer.validated_data['parent'],
body=serializer.validated_data['body'])
else:
comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'],
body=serializer.validated_data['body'])

comments_ser = CommentSerializer(comment,many=False, read_only=True).data
return Response(comments_ser, status=status.HTTP_200_OK)
return Response(status=status.HTTP_400_BAD_REQUEST)

最佳答案

你的线路

_comments = Comment.objects.filter(product=_product, parent__is_null=True)

应该是

_comments = Comment.objects.filter(product=_product, parent__isnull=True)

关于django - FieldError at/Related Field 得到无效查找 : is_null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64833665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com