Serialize and create one-to-one relation with parent_link true in django and django rest framework
How to save the object with one-to-one relation and having parent_link=True using serializer. Below are my models and serializer having some fields from the actual model that I wanted to implement. I am not able to save the 'user' relation in the database. It is throwing the integrity error.
class Audit(models.Model):
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now=True, null=True)
class Meta:
abstract = True
class User(Audit):
class Meta:
db_table = 'user'
email = models.EmailField(unique=True)
password = models.TextField()
is_active = models.BooleanField(default=False)
class UserProfile(User):
class Meta:
db_table = 'user_profile'
user = models.OneToOneField(User, on_delete=models.CASCADE, parent_link=True,
primary_key=True)
address = models.TextField(null=True)
dob = models.DateField()
language = models.CharField(max_length=50, null=True)
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ['user', 'address', 'dob', 'language']
And the requested data looks like this. { "email": "abc@pqr.com", "password": "1234", "dob": "2021-12-11", "language" : "English" }
You can pass user when saving serializer :
serializer.save(user=<USER>)
Note that if you want to create user when creating user profile, you should override create()
method in your serializer, first create your user, then create user profile, and pass created user to it