我在锦标赛序列化程序中创建了一个自定义创建字段来创建和更新嵌套字段。很长一段时间以来,我一直在努力做到这一点,但我无法摆脱错误。
当我试图在锦标赛更新上发布数据时,它会返回以下错误:
NOT NULL constraint failed: api_tournament.organizer_id
这里,api是应用程序的名称。
型号.py
class tournament(models.Model):
tournament_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=60)
organizer = models.ForeignKey(
client, null=False, blank=False, on_delete=models.CASCADE)
logo = models.ImageField(null=True, blank=False)
game = models.CharField(max_length=20, choices=GAMES)
fees = models.IntegerField()
def __str__(self):
return self.title
views.py
# tournament
@api_view(['GET'])
def tournamentList(request):
tournaments = tournament.objects.all()
serializer = tournamentSerializer(tournaments, many=True)
return Response(serializer.data)
@api_view(['GET'])
def tournamentDetail(request, tournamentId):
singleTournament = tournament.objects.get(tournament_id=tournamentId)
serializer = tournamentSerializer(singleTournament, many=False)
return Response(serializer.data)
@api_view(['POST'])
def tournamentCreate(request):
serializer = tournamentSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['POST'])
def tournamentUpdate(request, tournamentId):
singleTournament = tournament.objects.get(tournament_id=tournamentId)
serializer = tournamentSerializer(
instance=singleTournament, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['DELETE'])
def tournamentDelete(request, tournamentId):
singleTournament = tournament.objects.get(tournament_id=tournamentId)
singleTournament.delete()
return Response("Deleted Item")
serializers.py
class tournamentSerializer(serializers.ModelSerializer):
organizer = clientSerializer(many=False, read_only=False)
class Meta:
model = tournament
fields = "__all__"
def create(self, validated_data):
organizer_data = validated_data.pop('organizer')
new_tournament = tournament.objects.create(**validated_data)
client.objects.create(organizer_data)
return new_tournament
- "我在锦标赛序列化程序中创建了cusotm create字段来创建和更新嵌套字段,试图让它工作很长一段时间,但无法消除错误">
此错误与创建/更新嵌套字段无关。但如果你真的走上这条路:
当您使用实例初始化序列化程序并调用save((时,它不会调用create方法。它将调用序列化程序更新方法。这是用于证明的源代码。
if self.instance is not None:
self.instance = self.update(self.instance, validated_data)
assert self.instance is not None, (
'`update()` did not return an object instance.'
)
else:
self.instance = self.create(validated_data)
assert self.instance is not None, (
'`create()` did not return an object instance.'
)
return self.instance
但是序列化程序更新方法似乎不在您提供的代码中。它将默认为ModelSerializer的更新,这将引发有关嵌套写入的错误。既然事实并非如此,那么这个bug一定是更早出现的。这可能发生在serializer.is_valid((.内部
- "当我试图在锦标赛更新上发布数据时,它给出的错误为
NOT NULL constraint failed: api_tournament.organizer_id
">
该错误表示违反了阻止null值的约束。从外观上看,request.data可能没有";organizer_id";或";组织者";钥匙如果您想在更新过程中更新锦标赛而不发布所有数据,请给序列化程序字段参数required=False,或者用参数partial=True 初始化序列化程序