Miralem Cebic
Miralem Cebic

Reputation: 1286

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)

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.

Upvotes: 1

Views: 1584

Answers (1)

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41691

Your ForeignKey is on your FooBar model, not your Geopoint model. 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.

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.

Upvotes: 1

Related Questions