python - Integrity error while trying to serialize nested object using django rest framework -
model file
class address(models.model): address_id = models.autofield(primary_key=true, auto_created=true) address_data = models.charfield(max_length=250) class user(models.model): user_id = models.autofield(primary_key=true) name = models.charfield(max_length=50) address = models.foreignkey(address)
serializer file
class addressserializer(serializers.modelserializer): class meta: model = address fields = ('address_data') class userserializer(serializers.modelserializer): address = addressserializer() class meta: model = user fields = ('name', 'address') def create(self, validated_data): address_data = validated_data.pop('address') user = user.objects.create(**validated_data) address.objects.create(user=user, **address_data) return user
i have above code snippet in model , serializer file. getting integrity error while serializing , saving following object.
{"name": "john", "address": {"address_data": "some address"}}
i trying save 2 objects in 2 tables foreign key constraint. place feel erroring out user = user.objects.create(**validated_data)
because address
object still not created , trying save user
object without address
reference.
i checked django-rest-framework documentation. not able understand going wrong.
in userserializer model address. shouldn't user?
edit
your create method on userserializer should this:
def create(self, validated_data): address_data = validated_data.pop('address') address = address.objects.create(**address_data) validated_data['address'] = address user = user.objects.create(**validated_data)
your user has foreign key address, not passing on user's create method.
Comments
Post a Comment