我将仅粘贴问题的必要代码。 我有以下模型:
class Event(models.Model):
id = models.AutoField(primary_key=True)
序列化器:
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ('id', 'name')
@transaction.atomic
def create(self, validated_data):
print("before")
print(validated_data)
event = Event.objects.create(**validated_data)
print("after")
return event
我在第event = Event.objects.create(**validated_data)
行出现以下错误null value in column "id" violates not-null constraint
。当我打印经过验证的数据时,它不包含任何ID。我该如何解决我的问题?
答案 0 :(得分:0)
在DRF中,AutoField
字段默认为只读,您可以通过定义extra_kwargs
class EventSerializer(serializers.ModelSerializer):
id = serializers.IntegerField() # Here
class Meta:
model = Event
fields = ('id', 'name')
extra_kwargs = {'id': {'read_only': False}}
@transaction.atomic
def create(self, validated_data):
print("before")
print(validated_data)
event = Event.objects.create(**validated_data)
print("after")
return event