错误:
AttributeError at /stats/matches
Got AttributeError when attempting to get a value for field
players
on serializerMatchSerializer
. The serializer field might be named incorrectly and not match any attribute or key on theMatch
instance. Original exception text was: 'Match' object has no attribute 'players'.
模型:
每场比赛
有 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
在 Match
的实例中搜索 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
:
class MatchSerializer(serializers.ModelSerializer):
players = PlayerSerializer(many=True, source='player_set')
class Meta:
model = Match
fields = ("mid", "players")
希望对您有所帮助。
关于python - DRF一对多序列化——缺少字段的AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51181868/