2014-12-04 68 views
1

我有這樣的錯誤Django的REST框架3.0 - NOT NULL約束失敗:

IntegrityError at /foobars/ 
NOT NULL constraint failed: restServer_foobar.geo_location_id 

當我嘗試新的Foobar的對象超過http://127.0.0.1:8000/foobars/(網站/ APIView)

我的串行類看起來添加到DB像這樣:

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被刪除。

回答

1

您的ForeignKey是你的FooBar模型,而不是你的Geopoint模型。這決定了您創建對象所需的順序,因爲必須正確填寫數據庫中的字段。

帶外鍵的對象應始終在之後創建,因爲它們之後無法填充它 - 它在創建對象時必須存在。在您的情況下,這意味着您必須切換create對賬單的位置,因此在FooBar對象之前創建了Geopoint

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 

注意構造每個對象時的變化。

+0

謝謝解決我的問題。當我試圖通過一個簡單的iOS應用程序使用AFNetworking PUT foobar請求時,我得到一個錯誤的請求400錯誤。任何想法,爲什麼它通過Web/APIView而不是從一個像應用程序的「外部」請求? – 2014-12-04 21:43:30

相關問題