gpt4 book ai didi

python - Django REST 框架中的外键值

转载 作者:太空狗 更新时间:2023-10-29 17:29:38 24 4
gpt4 key购买 nike

模型.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 是所有处理关系的字段的基类。通常你不应该使用它,除非你将它子类化为一个自定义字段。

在您的情况下,您甚至根本不需要相关字段。您只是在寻找一个只读的单个外键表示,因此您可以只使用 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

关于python - Django REST 框架中的外键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28200485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com