将过滤器附加到django模型

时间:2014-11-24 22:02:49

标签: python django

上下文

嘿伙计们,

所以假设我有两个模型:属性通过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)
  • 属性可以是头发颜色,位置,大学学位等。
  • 因此,例如,某个属性可能具有“计算机科学”的“attribute_name”和“D”的“attribute_type”(对于学位)。
  • 另一个例子是'伦敦','L'。

问题

在此网页上,用户可以按属性选择人员。例如,他们可能希望看到所有居住在伦敦并且拥有历史和生物学学位(所有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')

但是,用户可以同样要求具有四种不同学位的用户。关键是,我们不知道用户在搜索功能中要求的属性数量。

问题

  • 因此,如果我们不知道有多少,以及用户要请求的属性类型,这是附加这些过滤器的最佳方式?
  • 以这种方式附加过滤器是最好的方法吗?

谢谢!

尼克

2 个答案:

答案 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是更好的方法。