[英]Django REST Framework 3.0 - NOT NULL constraint failed:
我有這個錯誤
IntegrityError at /foobars/
NOT NULL constraint failed: restServer_foobar.geo_location_id
當我嘗試通過http://127.0.0.1:8000/foobars/
(網站/ 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
注意構造每個對象的變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.