Django REST Framework - StringRelatedField
DRF tip:
To represent the target of the relationship with its
__str__
method, you can use StringRelatedField in the serializer. 👇# model: class Post(models.Model): # ... def __str__(self): return f"{self.date_published} - {self.title}" # serializer: class TagSerializer(serializers.ModelSerializer): posts = serializers.StringRelatedField(many=True) class Meta: model = Tag fields = ['name', 'posts'] # result: { "name": "Stories", "posts": [ "2022-01-09 - My first story", "2022-04-09 - Story about a dog" ] }