我很难使用django-filter实现或查询。我可以找到一些示例,讲述如何在django queryset中创建或查询。
但是,我在Django-Filter文档中找不到。有人知道如何使用Django-Filter实施或查询吗?model.py
和filter.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']
我不知道答案,但是我可以建议两种途径。
首先,您可以使用MultipleChoiceFilter
或TypedMultipleChoiceFilter
吗?(请参阅django-filter doc https://django-filter.readthedocs.io/en/develop/ref/ref/filters.html)
其次,Django-Filters建议您添加自定义过滤器类型。我认为这对应于添加到模型管理器或QuerySet中的自定义方法。为此,请咨询Django文档。这是我所知道的,但从来没有需要做。
我确实希望django-filters的文档更厚!
您可以使用Q对象进行复杂的查询集,也许这就是您需要的
https://docs.djangoproject.com/en/1.10/topics/db/queries/#complex-lookups-with-q-objects