【发布时间】:2021-01-17 01:30:59
【问题描述】:
我有一些项目的数据库查询 (containers)。
有一个相关表可以定义一些限制(仅限顶级org中的那些,只有dept中的那些(客户) org,或者只是 team 中的那些(课程)在 dept)
这是获取对象列表的(不工作的)代码:
def get_containers(customer_id: None, course_id: None):
q_list = (Q(is_private=False), Q(is_active=True))
if customer_id:
try:
customers = Customer.objects
customer = customers.get(id=customer_id)
except KeyError:
return None
# Second level restriction: may have a customer-id
customer_q = (
Q(restrictions__customer__isnull=True)
| Q(restrictions__customer=customer.id)
)
# Third level restriction: may be restricted to a course-code
course_q = Q(restrictions__course_code__isnull=True)
if course_id:
course_q |= Q(restrictions__course_code=course_id)
# Top level restriction: restricted to org
restrictions_q = (
Q(restrictions__organisation=customer.org.id)
& customer_q
& course_q
)
q_list = (Q(q_list) | Q(restrictions_q))
print(f"q_list: {q_list}")
return Container.objects.filter(q_list)
在此期间,我一直使用https://docs.djangoproject.com/en/3.0/topics/db/queries/#complex-lookups-with-q(和引用的https://github.com/django/django/blob/master/tests/or_lookups/tests.py)和之前询问的django dynamically filtering with q objects 作为引用。
我尝试了很多变体来让if customer_id: 块末尾的OR 工作 - 它们都给了我错误:
q_list = q_list | restrictions_q\nTypeError: unsupported operand type(s) for |: 'tuple' and 'Q'q_list = Q(q_list | restrictions_q)\nTypeError: unsupported operand type(s) for |: 'tuple' and 'Q'q_list |= restrictions_q\nTypeError: unsupported operand type(s) for |=: 'tuple' and 'Q'q_list.add(restrictions_q, Q.OR)\nAttributeError: 'tuple' object has no attribute 'add'
问题:如何创建q_list = q_list OR restrictions_q 构造?
【问题讨论】: