首页 > 解决方案 > DRF 一对多序列化——缺少字段的 AttributeError

问题描述

错误:

/stats/matches 处的 AttributeError

players尝试获取序列化程序上的字段值时出现 AttributeError MatchSerializer。序列化器字段可能命名不正确,并且与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")

标签: pythondjangodjango-rest-framework

解决方案


在的实例中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")

希望能帮助到你。


推荐阅读