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!
As stated in the documentation, you will need to write your own create() and update() methods in your serializer to support writable nested data. You will also need to explicitly add the status field instead of using the depth argument otherwise I believe it won't be automatically added to validated_data .
Your code is using serializer only for validation, but it is possible use it to insert or update new objects on database calling serializer. save() . To save foreign keys using django-rest-framework you must put a related field on serializer to deal with it. Use PrimaryKeyRelatedField .
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
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
.
class StationSerializer(serializers.ModelSerializer): station = serializers.CharField(read_only=True) class Meta: model = Station class FlatSerializer(serializers.ModelSerializer): station_name = serializers.CharField(source='station.name', read_only=True) class Meta: model = Flat fields = ('station_name', )
You also appear to want the name
of the Station
object in your FlatSerializer
. You should have the source
point to the exact field, so I updated it to station.name
for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With