gpt4 book ai didi

python - Django 主键序列化器 "This field may not be null"同时allow_null=True

转载 作者:行者123 更新时间:2023-12-01 02:54:54 25 4
gpt4 key购买 nike

我一直在为这个问题苦苦挣扎。

我不确定我错过了什么。

如果您有任何建议,请告诉我..!!

models.py:

co_manager = models.ManyToManyField(BookRunner, blank=True, null=True, related_name="deal_co_manager")

views.py:

 class DealAdminViewSet(viewsets.ModelViewSet):
queryset = Deal.objects.all()
serializer_class = CreateDealSerializer

def create(self, request, format=None):
data = ...all things data here.
serializer = CreateDealSerializer(data=deal)
print serializer
co_manager_array = []
if serializer.is_valid():
serializer.save()
return Response(status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

序列化器.py:

class CreateDealSerializer(serializers.Serializer):
co_manager = serializers.PrimaryKeyRelatedField(allow_null=True, many=True, queryset=BookRunner.objects.all(), required=False)

最佳答案

我建议编辑您的 View ,更像这样,

class DealAdminViewSet(viewsets.ModelViewSet):
queryset = Deal.objects.all()
serializer_class = CreateDealSerializer

def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

如果不展示您的模型,任何人可以提供的帮助都非常有限。如果有任何情况请告诉我。

此外,你的序列化器,

class CreateDealSerializer(serializers.Serializer):
co_manager = serializers.PrimaryKeyRelatedField(allow_null=True, many=True, queryset=BookRunner.objects.all())

触发错误的原因是,在您的模型中,字段 co_manager 未定义为 null=True。如果你想将上面的字段保存为null,那么在你的models.py中进行更改,

co_manager = models.ForeignKey(Target_table_name, null=True, blank=True)

当存储空值时,不会引发错误。

关于python - Django 主键序列化器 "This field may not be null"同时allow_null=True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44322002/

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