Django REST 框架中的外键值
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
然后在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()
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
是所有处理关系的字段的基础 class。通常你不应该使用它,除非你将它作为自定义字段的子class。
在您的情况下,您甚至根本不需要相关字段。您只是在寻找只读的单个外键表示,因此您可以只使用 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', )
您似乎还想要 FlatSerializer
中 Station
对象的 name
。您应该让 source
指向确切的字段,所以我为您将其更新为 station.name
。
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()
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!
RelatedField
是所有处理关系的字段的基础 class。通常你不应该使用它,除非你将它作为自定义字段的子class。
在您的情况下,您甚至根本不需要相关字段。您只是在寻找只读的单个外键表示,因此您可以只使用 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', )
您似乎还想要 FlatSerializer
中 Station
对象的 name
。您应该让 source
指向确切的字段,所以我为您将其更新为 station.name
。