[英]Django Rest framework post ForeignKey
I am using DRF to update data.我正在使用 DRF 来更新数据。 Its works good, but I am struggling how to update foreign keys.它工作得很好,但我正在努力如何更新外键。
{
"name": "Ready Or Not",
"releases": [
{
"platform": {
"name": "test"
},
"date": "2019-10-02T11:38:18Z"
}
]
},
This is a response of my API.这是我的 API 的回应。
But I want to update this 'releases' information as well.但我也想更新这个“发布”信息。
To sent I have this.要发送,我有这个。 If the 'platform' name doesnt exist it should also create one.如果“平台”名称不存在,它也应该创建一个。 How do I do this?我该怎么做呢?
headers = {
'Authorization': 'Token ' + ss_token,
}
data = {
"releases": [
{
"platform": {
"name": "wanttoupdate"
},
"date": "2019-10-02T11:38:18Z"
},
]
}
source = Source.objects.all().first()
url = source.url + str(947) + '/'
response = requests.patch(url, headers=headers, data=data)
My models:我的模型:
class Game(models.Model):
name = models.CharField(max_length=255)
class Platform(models.Model):
name = models.CharField(max_length=255)
class Release(models.Model):
platform = models.ForeignKey(Platform, on_delete=models.CASCADE)
game = models.ForeignKey(Game, related_name='releases', on_delete=models.CASCADE)
date = models.DateTimeField()
To post a ForeignKey instance, you have to use its id, for example in you case要发布 ForeignKey 实例,您必须使用它的 id,例如在您的情况下
if request.method == 'POST':
platform = request.POST['platform'] # pass your html name parameter
release_obj = Release(platform_id = platform)
release_obj.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.