我有这个错误
IntegrityError at /foobars/
NOT NULL constraint failed: restServer_foobar.geo_location_id
当我尝试通过 http://127.0.0.1:8000/foobars/
(Website/APIView) 将新的 Foobar 对象添加到数据库时
我的序列化器类如下所示:
class GeopointSerializer(serializers.ModelSerializer):
class Meta:
model = Geopoint
fields = ('id', 'latitude', 'longitude')
class FooBarSerializer(serializers.ModelSerializer):
geo_location = GeopointSerializer(required=True)
class Meta:
model = FooBar
fields = ('id', 'geo_location', 'geo_fence', 'registered', 'last_login')
def create(self, validated_data):
geo_location_data = validated_data.pop('geo_location')
foobar = FooBar.objects.create(**validated_data)
Geopoint.objects.create(FooBar=foobar, **geo_location_data)
return foobar
数据库已删除。
最佳答案
您的 ForeignKey
位于您的 FooBar
模型上,而不是您的 Geopoint
模型上。这决定了您创建对象所需的顺序,因为必须正确填写数据库中的字段。
具有外键的对象应始终在它们指向的对象之后创建,因为您无法在之后填充它 - 它必须在您创建对象时存在。就您而言,这意味着您必须切换 create
语句的位置,以便在 FooBar
对象之前创建 Geopoint
。 p>
def create(self, validated_data):
geo_location_data = validated_data.pop('geo_location')
geo_location = Geopoint.objects.create(**geo_location_data)
foobar = FooBar.objects.create(geo_location=geo_location, **validated_data)
return foobar
注意构造每个对象时的变化。
关于python - Django REST Framework 3.0 - NOT NULL 约束失败 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27303496/