DRF一对多序列化-缺少字段的AttributeError [英] DRF one to many serialization -- AttributeError from missing field

查看:189
本文介绍了DRF一对多序列化-缺少字段的AttributeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误:


/ stats / matches上的AttributeError

AttributeError at /stats/matches

Got AttributeError。
序列化程序字段的名称可能不正确,并且与 Match 实例上的任何属性或键都不匹配。
原始异常文本为:匹配对象没有属性玩家。

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


推荐答案

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

希望有帮助。

这篇关于DRF一对多序列化-缺少字段的AttributeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆