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

标签 python django django-rest-framework

错误:

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

最佳答案

MatchSerializerMatch 的实例中搜索 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/

相关文章:

python - celery 任务装饰器抛出 "TypeError: ' 模块对象不可调用”

python - 使用 selenium 和 firefox 保存图像

python - 使用 Python 压缩 Mac 应用程序包

python - 为了允许非 dict 对象被序列化,将 safe 参数设置为 False

python - Django View 接收不完整的 POST 负载

django - DRF 序列化程序通过请求用户通过 post 获取喜欢的数据

python - 在Django项目中获取typeError错误

python - Django 是 MVC 还是 MVT 框架?

Django 休息框架 : DRYer pagination for custom actions

django - django rest 中的分页,ListAPIView