Skip to main content
 首页 » 编程设计

python之DRF一对多序列化——缺少字段的AttributeError

2025年05月04日12unruledboy

错误:

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


模型:

每场比赛有 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") 

希望对您有所帮助。