上下文
嘿伙计们,
所以假设我有两个模型:人和属性通过ManyToMany关系连接(一个人可以有很多属性,一个属性可以被很多人共享)
class Attribute(models.model):
attribute_name = models.CharField(max_length=100)
attribute_type = models.CharField(max_length=1)
class Person(models.model):
article_name = models.CharField(max_length=100)
attributes = models.ManyToManyField(Attribute)
问题
在此网页上,用户可以按属性选择人员。例如,他们可能希望看到所有居住在伦敦并且拥有历史和生物学学位(所有AND关系)的人。
我知道这可以在下面表示(易读性的中断):
Person.objects
.filter(attributes__attribute_name='London', attributes__attribute_type='L')
.filter(attributes__attribute_name='History', attributes__attribute_type='D')
.filter(attributes__attribute_name='Biology', attributes__attribute_type='D')
但是,用户可以同样要求具有四种不同学位的用户。关键是,我们不知道用户在搜索功能中要求的属性数量。
问题
谢谢!
尼克
答案 0 :(得分:2)
您可以获取用户选择的所有属性,然后迭代:
# sel_att holds the user selected attributes.
result = Person.objects.all()
for att in sel_att:
result = result.filter(
attributes__attribute_name=att.attribute_name,
attributes__attribute_type=att.attribute_type
)
答案 1 :(得分:0)
使用Q模块进行复杂查找。
例如:
from django.db.models import Q
Person.objects.get(Q(attributes__attribute_name='London') | Q(attributes__attribute_name='History')
在QuerySet
范围内|
充当OR,而,
充当AND,与预期完全一样。
通道滤波器的问题是你只能在它们之间实现AND逻辑,对于复杂的AND,OR,NOT逻辑Q是更好的方法。