python - DRF 一对多序列化——缺少字段的 AttributeError
问题描述
错误:
/stats/matches 处的 AttributeError
players
尝试获取序列化程序上的字段值时出现 AttributeErrorMatchSerializer
。序列化器字段可能命名不正确,并且与Match
实例上的任何属性或键都不匹配。原始异常文本是:“匹配”对象没有属性“玩家”。
楷模:
每个Match
有 10 名玩家。
class Match(models.Model):
tournament = models.ForeignKey(Tournament, blank=True)
mid = models.CharField(primary_key=True, max_length=255)
mlength = models.CharField(max_length=255)
win_rad = models.BooleanField(default=True)
class Player(models.Model):
match = models.ForeignKey(Match, on_delete=models.CASCADE)
playerid = models.CharField(max_length=255, default='novalue')
# There is also a Meta class that defines unique_together but its omitted for clarity.
序列化器:
class PlayerSerializer(serializers.ModelSerializer):
class Meta:
model = Player
fields = "__all__"
class MatchSerializer(serializers.ModelSerializer):
players = PlayerSerializer(many=True)
class Meta:
model = Match
fields = ("mid","players")
解决方案
在的实例中MatchSerializer
搜索players
属性Match
,但找不到,您会收到以下错误:
AttributeError at /stats/matches
Got AttributeError when attempting to get a value for field players on
serializer MatchSerializer. The serializer field might be named
incorrectly and not match any attribute or key on the Match instance.
Original exception text was: 'Match' object has no attribute 'players'.
在 DRF 序列化器中,一个名为 source 的参数将明确告诉在哪里查找数据。所以,改变你MatchSerializer
如下:
class MatchSerializer(serializers.ModelSerializer):
players = PlayerSerializer(many=True, source='player_set')
class Meta:
model = Match
fields = ("mid", "players")
希望能帮助到你。
推荐阅读
- ios - 如何在结构中获取随附的 var 值?
- elasticsearch - Elasticsearch bool 查询,检查属性是否完全丢失,或者属性是否存在并包含特定字符串
- java - 使用 regionMatches 而不是 compareTo() 比较字符串
- r - 在R中按等级排序
- javascript - Chrome 控制台日志不起作用!我需要帮助上课吗?
- ios - 将 currentTime 设置为 0.0 后,AVAudioPlayer 随机不播放
- javascript - 每次渲染组件时调用一个函数,因为 componentDidMount() 只触发一次
- java - 将值输入到几个数组中
- c# - 查找除特定列之外的 DataTable 的空单元格
- python - 未定义全局名称“bigquery”