So I have a custom model - Profile, which has a OneToOne relation with a django User object.
class Profile(models.Model):
user = OneToOneField(User, on_delete=models.CASCADE)
profile_type = models.CharField()
I want to make a django rest framework serializer which allows for creation of creation and retrieval of a User object's nested attributes as well as the "profile_type" attribute.
I want the names to be specified on the POST request as simply as "username", "password", "email", etc. - instead of "profile_username", "profile_password", ...
So far I have
class ProfileSerializer(serializers.ModelSerializer):
username = serializers.CharField(source='profile_user_username')
password = serializers.CharField(source='profile_user_password')
email = serializers.CharField(source='profile_user_email')
class Meta:
model = Profile
fields = ('id',
'profile_user_username', 'profile_user_password', 'profile_user_email',
'username',
'password',
'email')
depth = 2
But - I've been getting an error:
ImproperlyConfigured: Field name 'profile_user_username' is not valid for model 'Profile'
Am I getting the syntax for nested fields wrong? Or is it something else?
Try:
class User(models.Model):
username = models.CharField()
password = models.CharField()
email = models.CharField()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
class ProfileSerializer(serializers.ModelSerializer):
user = UserSerializer(many=True)
class Meta:
model = Profile
fields = ('user', 'profile_type',)
def create(self, validated_data):
user_data = validated_data.pop('user')
user = User.objects.create(**user_data)
profile = Profile.objects.create(user=user, **validated_data)
return profile
and check out this for Writable nested serializers.
For dealing a nested object: checkout this this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With