或者在django-filter中查询

时间:2017-02-16 12:19:21

标签: python django django-filter

我很难使用django-filter实现OR查询。我找到了some example telling how to create OR query in django queryset

但是,我在django-filter文档中找不到。有谁知道如何使用django-filter实现OR查询? model.pyfilter.py如下所示。

model.py

class html(models.Model):
    project = models.CharField(max_length=50, blank=True)
    version = models.IntegerField(default=0)
    ecms=models.ManyToManyField(ecm, blank=True)
    diff = models.TextField(blank=True)
    PROGRAM_CHOICES = (
        ('Office', 'General office'),
        ('Residential', 'Residential'),
        ('Retail', 'Retail'),
        ('Restaurant', 'Restaurant'),
        ('Grocery', 'Grocery store'),
        ('Medilcal', 'Medilcal office'),
        ('Research', 'R&D or laboratory'),
        ('Hotel', 'Hotel'),
        ('Daycare', 'Daycare'),
        ('K-12', 'Educational,K-12'),
        ('Postsecondary', 'Educational,postsecondary'),
        ('Airport', 'Airport'),
        ('DataCenter','Data Center'),
        ('DistributionCenter','Distribution center,warehouse')
    )
    program = models.CharField(max_length=20, choices=PROGRAM_CHOICES, default='Retail')
    LOCATION_CHOICES = (
        ('Beijing', 'Beijing'),
        ('China', 'China'),
        ('Hong Kong', 'Hong Kong'),
        ('Japan', 'Japan'),
        ('Shanghai', 'Shanghai'),
        ('Shenzhen', 'Shenzhen'),
        ('Taiwan', 'Taiwan')
    )
    location = models.CharField(max_length=15, choices=LOCATION_CHOICES, default="Hong Kong")
    CERTIFICATE_CHOICES = (
        ('LEED_v3', 'LEED_v3'),
        ('LEED_v4', 'LEED_v4'),
        ('BEAM+', 'BEAM+'),
        ('WELL', 'WELL')
    )
    certificate = models.CharField(max_length=10, choices=CERTIFICATE_CHOICES, default='BEAM+')
    user = models.CharField(max_length=20, default='test')
    html = models.FileField(upload_to=dir_path)
    uploaded_at = models.DateTimeField(auto_now_add=True)

filter.py

import django_filters
from .models import html

class ProjectFilter(django_filters.FilterSet):
    class Meta:
        model=html
        fields=['project','program','location','certificate','user']

2 个答案:

答案 0 :(得分:0)

我不知道答案,但我可以建议两种途径。

首先,您可以使用MultipleChoiceFilterTypedMultipleChoiceFilter吗? (请参阅django-filter doc https://django-filter.readthedocs.io/en/develop/ref/filters.html

其次,django-filters建议您可以添加自定义过滤器类型。我认为这对应于添加到模型管理器或查询集的自定义方法。有关这些,请参阅Django文档。这是我所知道的,但从未需要做过。

我希望django-filters文档更厚一些!

答案 1 :(得分:0)

您可以使用Q对象制作复杂的查询集,也许这就是您需要的

https://docs.djangoproject.com/en/1.10/topics/db/queries/#complex-lookups-with-q-objects