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

时间:2018-07-04 23:54:57

标签: python django django-rest-framework

错误:

  

/ stats / matches处的AttributeError

     

尝试在序列化程序players上获取字段MatchSerializer的值时出现AttributeError。   序列化程序字段的名称可能不正确,并且与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.

序列化器:

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")

2 个答案:

答案 0 :(得分:3)

MatchSerializerplayers的实例中搜索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'.

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

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

希望有帮助。

答案 1 :(得分:2)

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

您可以通过两种方法
解决此问题 1。。向source

添加一个PlayerSerializer参数
class MatchSerializer(serializers.ModelSerializer):
    players = PlayerSerializer(many=True, source='player_set')
    class Meta:
        model = Match
        fields = ("mid", "players")

2。。更改查找字段

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