Foreign key value in Django REST Framework

2019-03-25 14:56发布

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!

1条回答
叼着烟拽天下
2楼-- · 2019-03-25 15:12

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.

查看更多
登录 后发表回答