我正在使用DeliciousPie发出POST请求。 Task模型通过parent_task_id字段具有一对多的自引用关系。
型号:
class Task(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
parent_task_id = models.ForeignKey(
"self",
on_delete=models.CASCADE,
null=True, blank=True)
在我的api.py中
class TaskResource(ModelResource):
parent_task_id_id = fields.ToOneField('self', 'id', null=True, full=True)
class Meta:
queryset = Task.objects.all()
authorization = Authorization()
allowed_methods = ['post']
resource_name = "create_task"
使用邮递员指定parent_task_id时,无法创建任务。
{
"title": "ABCDERT",
"description": "world this week",
"due_date": "2018-11-12 1:2:1",
"parent_task_id_id": "2"
}
这是我收到的错误消息:
"error_message": "An incorrect URL was provided '2' for the 'CreateTaskResource' resource.",
答案 0 :(得分:1)
您应该指定parent_task的uri
而不是id
,例如
{
"title": "ABCDERT",
"description": "world this week",
"due_date": "2018-11-12 1:2:1",
"parent_task_id_id": "/create_task/2"
}
此外,以这种方式在资源中定义外键字段是错误的,
class TaskResource(ModelResource):
parent_task_id_id = fields.ToOneField('self', 'id', null=True, full=True)
您可以查看docs了解详情。
我调整您的示例,例如: 型号:
class Task(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
parent_task = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True)
api.py
class TaskResource(ModelResource):
parent_task = fields.ToOneField('self', 'parent_task', null=True,
full=True)
class Meta:
queryset = Task.objects.all()
authorization = Authorization()
allowed_methods = ['post', 'get']
filtering = {'id': ALL, 'parent_task': ALL_WITH_RELATIONS}
resource_name = "task"
POST正文,例如:
{
"title": "task2",
"description": "world this week",
"due_date": "2018-11-12 1:2:1",
"parent_task":"/api/v1/task/1/"
}
GET参数,如:
0.0.0.0:8000/api/v1/task/?parent_task__id=1