[英]Django REST Framework 3.0 - NOT NULL constraint failed:
I have this Error 我有这个错误
IntegrityError at /foobars/
NOT NULL constraint failed: restServer_foobar.geo_location_id
When I try to add a new Foobar Object to DB over http://127.0.0.1:8000/foobars/
(Website/APIView) 当我尝试通过
http://127.0.0.1:8000/foobars/
(网站/ APIView)向数据库添加新的Foobar对象时
My Serializer Class looks like this: 我的序列化器类如下所示:
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
DB was deleted. 数据库已删除。
Your ForeignKey
is on your FooBar
model, not your Geopoint
model. 您的
ForeignKey
在FooBar
模型上,而不在Geopoint
模型上。 This determine the order that you need to create objects, because the fields in the database have to be filled correctly. 这确定了创建对象所需的顺序,因为必须正确填写数据库中的字段。
Objects which have foreign keys should always be created after the objects that they point to, because you can't fill it in afterwards - it has to exist when you create the object. 具有外键的对象应始终在它们指向的对象之后创建,因为您以后不能再填写-创建对象时它必须存在。 In your case, that means you have to switch the location of your
create
statements, so the Geopoint
is created before the FooBar
object. 在您的情况下,这意味着您必须切换
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
Note the changes in constructing each object. 注意构造每个对象的变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.