DRF一对多序列化-缺少字段的AttributeError

Phi*_*wan 1 python django django-rest-framework

错误:

/ 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.
Run Code Online (Sandbox Code Playgroud)

序列化器:

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")
Run Code Online (Sandbox Code Playgroud)

mre*_*han 5

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'.
Run Code Online (Sandbox Code Playgroud)

在DRF序列化程序中,一个名为source的参数将明确告诉在哪里寻找数据。因此,将您的更改MatchSerializer如下:

class MatchSerializer(serializers.ModelSerializer):
    players = PlayerSerializer(many=True, source='player_set')
    class Meta:
        model = Match
        fields = ("mid", "players")
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。