简体   繁体   中英

Foreign key value in Django REST Framework

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 want ReadOnlyField .
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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM