Reputation: 941
I know it is relatively simple to change a represented filed name in the serializer with source
argument like this:
class SomeSerializer(ModelSerializer):
alternate_name = serializers.SomeField(source='field_name')
class Meta:
fields = ('alternate_name')
But when dealing with a many to many field, the source
is a ManyRelatedManager
and using source
in it leads to errors:
class SomeModel(models.Model):
field_name = models.ManyToManyField(OtherModel, related_name='groups')
class SomeModelSerializer(ModelSerializer):
alternate_name = models.ListField(source='field_name')
class Meta:
fields = ('alternate_name')
This gives ManyRelatedManager object is not iterable!
Using other Fields instead of ListField
gives other errors. What is the right approach here?
Upvotes: 0
Views: 275
Reputation: 1241
You can use obj.field_name.filter()
to get the related data and return this from SerializerMethodField()
as stated above.
This is how I would do it not sure if it works for you.
class SomeModel(models.Model):
field_name = models.ManyToManyField(OtherModel, related_name='groups')
class SomeModelSerializer(ModelSerializer):
#name this field whatever you want
some_name = serializers.SerializerMethodField()
# SerializerMethodField gets populated from "get_{filed_name}" method
def get_some_name(self, obj):
#this will return a list
return obj.field_name.filter()
class Meta:
fields = ('some_name')
Upvotes: 1