我一直在努力解决这个问题。
我不确定我错过了什么。
如果您有任何建议,请告诉我。!!
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)
serializer.py :
class CreateDealSerializer(serializers.Serializer):
co_manager = serializers.PrimaryKeyRelatedField(allow_null=True, many=True, queryset=BookRunner.objects.all(), required=False)
答案 0 :(得分:0)
我建议编辑你的观点,更像是这样,
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)
存储空值时,不会引发错误。
答案 1 :(得分:0)
如果设置了序列化器,只需发送一个空列表 许多=正确, allow_null =真
来自serliazer:
many_field = serializers.PrimaryKeyRelatedField(queryset=qs, read_only=False, many=True, allow_null=True)
class Meta:
model = ModelName
fields = (
'many_field ',
...)
extra_kwargs = {
'many_field': {'required': False},
}
以及请求数据中的
data = {'NOT_many_field': None,
'many_field': []}