Django 当模型具有一对多自引用关系时,如何使用TastyPie创建记录?
我正在使用TastyPie进行POST请求。任务模型通过父任务id字段具有一对多自引用关系 型号:Django 当模型具有一对多自引用关系时,如何使用TastyPie创建记录?,django,django-models,tastypie,Django,Django Models,Tastypie,我正在使用TastyPie进行POST请求。任务模型通过父任务id字段具有一对多自引用关系 型号: class Task(models.Model): title = models.CharField(max_length=100) description = models.TextField() parent_task_id = models.ForeignKey( "self", on_delete=models.CAS
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"
当我使用邮递员指定父任务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.",
您应该指定父任务的uri而不是id,如 { 标题:ABCDERT, 描述:世界本周, 截止日期:2018-11-12 1:2:1, 父任务\u id\u id:/create\u task/2 } 另外,用这种方式在资源中定义foreignkey字段是不正确的 类TaskResourceModelResource: 父任务\u id\u id=fields.ToOneField'self',id',null=True,full=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"
创建任务
类似于以下主体的帖子:
{
标题:任务2,
描述:世界本周,
截止日期:2018-11-12 1:2:1,
父任务:/api/v1/task/1/
}
外键查询
获取如下参数:
0.0.0.0:8000/api/v1/task/?parent_task_id=1将外键更改为parent_task_id=fields。外键“self”、“id”、null=True。我可以使用资源uri作为父任务id创建一个记录。但是每当我使用父任务id进行查询时,无论传递了什么值,它都会返回所有记录。它不会根据提供的外键进行过滤。
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"