I have my User
saved in two different models, UserProfile
and User
. Now from API perspective, nobody really cares that these two are different.
So here I have:
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'first_name', 'last_name', 'email')
and
class UserPSerializer(serializers.HyperlinkedModelSerializer):
full_name = Field(source='full_name')
class Meta:
model = UserProfile
fields = ('url', 'mobile', 'user','favourite_locations')
So in UserPSerializer
the field user
is just a link to that resource. But form a User perspective there is really no reason for him to know about User
at all.
Is there some tricks with which I can just mash them together and present them to the user as one model or do I have to do this manually somehow.
You can POST and PUT with @kahlo's approach if you also override the create and update methods on your serializer.
Given a profile model like this:
Here's a user serializer that both reads and writes the additional profile field(s):
The resulting API presents a flat user resource, as desired:
and you can include the profile's
avatar_url
field in both POST and PUT requests. (And DELETE on the user resource will also delete its Profile model, though that's just Django's normal delete cascade.)The logic here will always create a Profile model for the User if it's missing (on any update). With users and profiles, that's probably what you want. For other relationships it may not be, and you'll need to change the update-or-create logic. (Which is why DRF doesn't automatically write through a nested relationship for you.)
I just came across this; I have yet to find a good solution particularly for writing back to my
User
andUserProfile
models. I am currently flattening my serializers manually using theSerializerMethodField
, which is hugely irritating, but it works:This is horribly manual, but you do end up with:
Which, I guess is what you're looking for.
I would implement the modifications on the
UserPSerializer
as the fields are not going to grow: