且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-11-11 20:42:20

Match MatchSerializer 搜索 players 属性中实例,但找不到它,您会遇到以下错误:

The MatchSerializer search for a players attribute in Match's instance, but it couldn't find and you get the following error:

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

In DRF serializer, a parameter called source will tell explicitly where to look for the data. So, change your MatchSerializer as follow:

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

希望有帮助。