我有一个这样的模型:
class Task(models.Model):
created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='tasks_by_me')
assignees = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='tasks_assigned_to_me')
我想获取“由TheUser创建或分配给他的所有任务(没有重复)”。
这是我可以用SQL编写代码的方法:
SELECT *
FROM
(
SELECT 1 AS id, 1 as created_by_id UNION ALL
SELECT 2 AS id, 2 as created_by_id UNION ALL
SELECT 3 AS id, 3 as created_by_id UNION ALL
SELECT 4 AS id, 2 as created_by_id
) task
LEFT JOIN
(
SELECT 1 AS task_id, 1 AS user_id UNION ALL
SELECT 1 AS task_id, 2 AS user_id UNION ALL
SELECT 2 AS task_id, 1 AS user_id UNION ALL
SELECT 2 AS task_id, 2 AS user_id UNION ALL
SELECT 2 AS task_id, 3 AS user_id UNION ALL
SELECT 3 AS task_id, 3 AS user_id UNION ALL
SELECT 4 AS task_id, 2 AS user_id
) task_assignees ON task_assignees.task_id = task.id AND COALESCE(task_assignees.user_id, 2) = 2
WHERE task.created_by_id = 2
OR task_assignees.user_id = 2;
输出:
id created_by_id task_id user_id
1 1 1 2
2 2 2 2
4 2 4 2
注意:task_id=2
只有一行,尽管它有3个受理人并且任务是由TheUser(id=2)
创建的
我对处理这些场景的最佳做法感兴趣吗?
答案 0 :(得分:0)
您可以使用QuerySet API来使用django orm模型,而不是编写原始sql查询。下面的示例将为您提供分配给您的任务或您创建的任务的查询集。 Q
用于在django orm
from django.db.models import Q
Task.objects.filter(Q(assignees__username='soemeusername') | Q(created_by__username='someusername')).distinct()