DRF一对多序列化AttributeError from missing field

2024-04-25 22:15:04 发布

您现在位置:Python中文网/ 问答频道 /正文

错误:

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'.


型号:

每个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.

序列化程序:

^{pr2}$

Tags: truefieldforonmodelsmatchattributelength
2条回答

这里的问题是,Match模型没有一个名为players的属性,请记住,您正在尝试获取向后关系对象,因此您需要使用djangodocs所说的players_set作为字段。在

你可以用两种方法来解决这个问题 1。PlayerSerializer添加一个source参数

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

2。更改查找字段

^{pr2}$

MatchSerializerMatch的实例中搜索players属性,但找不到,并出现以下错误:

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

^{pr2}$

希望有帮助。在

相关问题 更多 >