我有这个错误
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
语句的位置,因此Geopoint
会在FooBar
对象之前创建。
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
注意构造每个对象时的更改。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句