I have a parent and mutually related child model, and I would like to display the fields from the child in the parent view ( read only ). Currently, I have achieved this with a custom implementation of to_representation , but it seems very attractive, and I wonder if there is an easier way to achieve this.
This is complicated by the fact that my related model is connected through a property.
So, here is a specific example: By default, a related object will be displayed as follows:
{ parent_name:'Bob', child:{ name:'Alice' } }
This is what I want and currently get with my to_representation :
{ parent_name:'Bob', child_name:'Alice' }
My models look like this:
class ChildModel(models.Model): name = models.CharField(max_length=100, null=True) class ParentModel(models.Model): name = models.CharField(max_length=100, null=True) _child = models.ForeignKey('ChildModel', null=True) @property def child(self): return self._most_recent_status @name.setter def child(self, value): self._child = value
Here are my serializers:
class FlatChildField(serializers.RelatedField): def to_representation(self, value): return value.name class FlatParentSerializer(serializers.ModelSerializer): parent_name = serializers.CharField(source='name', read_only=True) child_name = FlatChildField(source='_child', read_only=True) class Meta: model = Parent fields = ('name', 'child_name')
For a simpler solution to get a flat view of related models, I would appreciate it.
For completeness, I would be interested to hear if there is a simpler solution for βnormalβ coupled models (ie not property model fields). I was looking for the equivalent of the django model query syntax for related_model__field , but I cannot find this. Does this exist for the django rest framework?
Thank you very much