models.py:
class Station(models.Model):
station = models.CharField()
class Flat(models.Model):
station = models.ForeignKey(Station, related_name="metro")
# another fields
Then in serializers.py:
class StationSerializer(serializers.ModelSerializer):
station = serializers.RelatedField(read_only=True)
class Meta:
model = Station
class FlatSerializer(serializers.ModelSerializer):
station_name = serializers.RelatedField(source='station', read_only=True)
class Meta:
model = Flat
fields = ('station_name',)
And I have an error:
NotImplementedError:
RelatedField.to_representation()
must be implemented. If you are upgrading from REST framework version 2 you might wantReadOnlyField
.
I read this, but it does not help me.
How to fix that?
Thanks!
RelatedField
is the base class for all fields which work on relations. Usually you should not use it unless you are subclassing it for a custom field.In your case, you don't even need a related field at all. You are only looking for a read-only single foreign key representation, so you can just use a
CharField
.You also appear to want the
name
of theStation
object in yourFlatSerializer
. You should have thesource
point to the exact field, so I updated it tostation.name
for you.