Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF Serializer Nested Field for User Creation

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?

like image 810
codepringle Avatar asked Feb 16 '26 04:02

codepringle


1 Answers

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

like image 128
bluebird_lboro Avatar answered Feb 17 '26 18:02

bluebird_lboro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!