问题
I want to be able to access a userprofile
instance through :profile = instance.userprofile
statement in UserSerializer
instance
is created through:instance = super(UserSerializer, self).update(instance, validated_data)
statement in
UserSerializer
Since UserSerializer
is inheriting UserDetailsSerializer
, i think i should define a userprofile
in UserDetailsSerializer
.
But i dont know how to do it ?
Question: How to define userprofile
in UserDetailsSerializer
to achieve the above ?
UserSerializer:
class UserSerializer(UserDetailsSerializer):
company_name = serializers.CharField(source="userprofile.company_name")
class Meta(UserDetailsSerializer.Meta):
fields = UserDetailsSerializer.Meta.fields + ('company_name',)
def update(self, instance, validated_data):
profile_data = validated_data.pop('userprofile', {})
company_name = profile_data.get('company_name')
instance = super(UserSerializer, self).update(instance, validated_data)
# get and update user profile
profile = instance.userprofile
if profile_data and company_name:
profile.company_name = company_name
profile.save()
return instance
UserDetailsSerializer:
class UserDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('username','email', 'first_name', 'last_name')
read_only_fields = ('email', )
UserProfile model:
class UserProfile(models.Model):
user = models.OneToOneField(User)
# custom fields for user
company_name = models.CharField(max_length=100)
Do ask if more clarity is required?
回答1:
I think you want a serializer methodfield to be part of your serializer? (I don't full understand your question);
class UserDetailsSerializer(serializers.ModelSerializer):
user_related = serializers.Field(source='method_on_userprofile')
class Meta:
model = UserProfile
fields = ('username','email', 'first_name', 'user_related', )
read_only_fields = ('email', 'user_related',)
回答2:
I think I have answered similar one here
In the documentation it is assumed that userprofile was already created and now can be updated. You just need a check
# get and update user profile
try:
profile = instance.userprofile
except UserProfile.DoesNotExist:
profile = UserProfile()
if profile_data and company_name:
来源:https://stackoverflow.com/questions/32550317/how-to-define-a-userprofile-into-userdetialsserializer