Reputation: 816
I'm using DRF and I have a Profile serializer with a group field that is a foreignKey to Group model. Profile Serializer:
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ('group', ...)
Profile Model:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
# other fields
group = models.ForeignKey(Group, on_delete=models.CASCADE)
Group Model:
class Group(models.Model):
title = models.CharField(max_length=100)
def __str__(self):
return self.title
Group Serializer:
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('title', 'id')
extra_kwargs = {'id': {'read_only': True}}
I have a route in my SPA that showing a list of profiles. I want to show the group title for each profile but this serializer only provide me an id of group and I don't want to create another view to get id of group and give me title. so I search about it and it was 2 solution first StringRelatedField
that is read_only
and SlugRelatedField
. I changed ProfileSerializer
and add SlugRelatedField
like this:
class ProfileForAdminSerializer(serializers.ModelSerializer):
group = serializers.SlugRelatedField(
many=False,
queryset=Group.objects.all(),
slug_field='title'
)
class Meta:
model = Profile
fields = ('group', ...)
now I have access to title of profile group but the problem is I have to create Profile with providing title of group field, but I want to create Profile like before with sending id of group and also have access to title of group without send another request. (sorry for bad English)
Upvotes: 0
Views: 284
Reputation: 3588
Have you considered source
argument on serializer field ?
It should be something like this
group_title = serializers.ReadOnlyField(source='group.title')
class Meta:
...
fields = ('group_title', ...)
Upvotes: 2