Reputation: 1306
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 the above code snippet in the model and serializer file. I am getting a integrity error while serializing and saving the following object.
{"name": "John", "address": {"address_data": "some address"}}
I am trying to save two objects in 2 tables with a foreign key constraint. The place where I feel its erroring out is
user = User.objects.create(**validated_data)
because address
object is still not created and I am trying to save the user
object without the address
reference.
I checked all the django-rest-framework documentation. I am not able to understand where I am going wrong.
Upvotes: 1
Views: 1609
Reputation: 584
In your UserSerializer the model is Address. Shouldn't it be User?
Your create method on the UserSerializer should be like 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 to Address, but you were not passing that on to the User's create method.
Upvotes: 1