Django REST - 在串行器中解析外键和M2M

时间:2014-03-13 14:42:13

标签: json django rest serialization

我有以下型号:

class Player(models.Model):
    name = models.CharField(max_length=30)

class Achievement(models.Model):
    name = models.CharField(max_length=30)

class UnlockedAchievement(models.Model):
    achievement = models.ForeignKey(Achievement)
    date = models.DateTimeField()    

class PlayerAchievements(models.Model):
    player = models.ForeignKey(Player)
    unlocked_achievements = models.ManyToManyField(UnlockedAchievement, related_name="unlocked_achievements", blank=True, null=True)

使用PUT,我试图解决玩家的外键以及所有成就的嵌套关系。我的JSON数据实际上看起来像这样:

{"name":"playername",
    "achievements":
    {
        "ach1":"timestamp",
        "ach2":"timestamp",
    }
}

我能弄清楚的是使用哪种串行器的神奇组合,以及使用它们时,使用哪些序列化器字段或嵌套序列化器来通过名称来解析播放器,以及通过提供名称解锁的成就(以及他们的成就外键)。

在这种情况下,我无法访问身份证号码,因此事情是通过名字完成的。

看起来这种奇怪的混合物。任何人都可以伸出援手吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用nested relationships完全包含相关模型的序列化:

class AchievementSerializer(serializers.ModelSerializer):
    class Meta:
        model = Achievement

class UnlockedAchievementSerializer(serializers.ModelSerializer):
    achievement = AchievementSerializer(many=False)

    class Meta:
        model = UnlockedAchievement

class PlayerAchievementsSerializer(serializers.ModelSerializer):
    unlocked_achievements = UnlockedAchievementSerializer(many=True)

    class Meta:
        model = PlayerAchievements

class PlayerSerializer(serializers.ModelSerializer):
    player_achievements = PlayerAchievementsSerializer(many=False)

    class Meta:
        model = Player

然后只按名称过滤Player对象并序列化它。