1๐
You can use the source attribute of a serializer field to bring related object fields to the top level.
class MySerializer(serializers.ModelSerializer):
group_name = serializers.CharField(source='section.group.group_name')
class Meta:
model = MyModel
fields = ('group_name',)
However, this does not remove the performance implications of fetching related objects so select_related and prefetch_related on your queryset are still needed for optimal performance.
๐คMark Galloway
0๐
Filter is related to model, not its serializer version, so even if you will create field group_name
in serializer output โ it will not help with filtering. So actually I recommend you to post question about RelatedFilter
.
Answer to your question:
You can use SerializerMethodField to add custom field to object representation.
class MyModelSerializer(serializers.ModelSerializer):
group_name = serializers.SerializerMethodField()
class Meta:
model = MyModel
def get_group_name(self, obj):
return obj.group_name
๐คzymud
- Can django authentication be combined with django rest framework basic auth?
- Effectively use Multi-table inheritance (one-to-one relationships)
- How to handle view throwing manual exception in django in unit-testing?
Source:stackexchange.com