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',)

我有一个错误:

最佳答案

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

10-08 01:36