如何在HTTP POST中引用ForeignKey对象?

时间:2017-09-08 21:10:29

标签: django post django-rest-framework put

我在Django上有一个RESTful API,我想知道在HTTP POST中使用json时如何引用现有的ForeignKey?

class Trainer(models.Model):
    account = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='profiles')
    username = models.CharField(max_length=30, unique=True, primary_key=True)
    start_date = models.DateField(default=date(2016,7,13), null=True, blank=True)
    faction = models.ForeignKey('Faction', on_delete=models.SET_DEFAULT, default=0, null=True, verbose_name="team")
    has_cheated = models.BooleanField(default=False)
    last_cheated = models.DateField(null=True, blank=True)
    currently_cheats = models.BooleanField(default=False)
    statistics = models.BooleanField(default=True)
    daily_goal = models.IntegerField(null=True, blank=True)
    total_goal = models.IntegerField(null=True, blank=True)
    last_modified = models.DateTimeField(auto_now=True)
    prefered = models.BooleanField(default=True, verbose_name="main profile")

    def __str__(self):
        return self.username

class Faction(models.Model):
    name = models.CharField(max_length=140)
    colour = RGBColorField(default='#929292', null=True, blank=True)
    image = models.ImageField(upload_to=factionImagePath, blank=True, null=True)
    leader_name = models.CharField(max_length=140, null=True, blank=True)
    leader_image = models.ImageField(upload_to=leaderImagePath, blank=True, null=True)

    def __str__(self):
        return self.name

这是相关模型,我有4个Faction对象的列表,其主键为0,1,2和3.

我尝试了许多不同的方式,但我无法弄明白。 这是我最近的尝试,你能告诉我哪里出错吗?

{
    "username": "Bob123",
    "faction": "1"
}

返回的

{
    "username": "Bob123",
    "faction": "Teamless",
    "start_date": "2016-07-13",
    "has_cheated": false,
    "last_cheated": null,
    "currently_cheats": false,
    "statistics": true,
    "daily_goal": null,
    "total_goal": null,
    "last_modified": "2017-09-08T21:05:18.001389Z",
    "prefered": true,
    "account": null
}

编辑:我的朋友帮我解决了问题,我在Trainer的序列化程序中有faction = serializers.StringRelatedField(),它是只读的。

1 个答案:

答案 0 :(得分:0)

我的朋友帮我解决了这个问题,我在Trainer的序列化程序中有1faction = serializers.StringRelatedField()1,它是只读的。