Django REST Framework中的外键值

时间:2015-01-28 19:12:38

标签: python django rest 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

然后在 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',)

我有一个错误:

  

NotImplementedError:必须实现RelatedField.to_representation()。   如果要从REST框架版本2升级,则可能需要ReadOnlyField   我看了this,但它对我没有帮助   如何解决?
  谢谢!

1 个答案:

答案 0 :(得分:15)

RelatedField是处理关系的所有字段的基类。通常您不应该使用它,除非您将其子类化为自定义字段。

在您的情况下,您甚至根本不需要相关领域。您只需要查找只读的单个外键表示,因此您只需使用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', )

您似乎也希望name中的Station对象FlatSerializer。您应该将source指向确切的字段,因此我已将其更新为station.name