Python 将类与django筛选器关联
你好,我有一个关于django过滤器的问题。我的问题是: 我在models.py中定义了两个类:Python 将类与django筛选器关联,python,django,django-filter,django-filters,Python,Django,Django Filter,Django Filters,你好,我有一个关于django过滤器的问题。我的问题是: 我在models.py中定义了两个类: class Volcano(models.Model): vd_id = models.AutoField("ID, Volcano Identifier (Index)", primary_key=True) [...] class VolcanoInformation(models.Model): # Primary
class Volcano(models.Model):
vd_id = models.AutoField("ID, Volcano Identifier (Index)",
primary_key=True)
[...]
class VolcanoInformation(models.Model):
# Primary key
vd_inf_id = models.AutoField("ID, volcano information identifier (index)",
primary_key=True)
# Other attributes
vd_inf_numcal = models.IntegerField("Number of calderas")
[...]
# Foreign key(s)
vd_id = models.ForeignKey(Volcano, null=True, related_name='vd_inf_vd_id',
on_delete=models.CASCADE)
它们两个通过vd_id属性链接
我想开发一个搜索工具,允许用户根据火山口的数量来搜索火山
我正在使用django过滤器,现在这里是我的filters.py:
from .models import *
import django_filters
class VolcanoFilter(django_filters.FilterSet):
vd_name = django_filters.ModelChoiceFilter(
queryset=Volcano.objects.values_list('vd_name', flat=True),
widget=forms.Select, label='Volcano name',
to_field_name='vd_name',
)
vd_inf_numcal = django_filters.ModelChoiceFilter(
queryset=VolcanoInformation.objects.values_list('vd_inf_numcal', flat=True),
widget=forms.Select, label='Number of calderas',
)
class Meta:
model = Volcano
fields = ['vd_name', 'vd_inf_numcal']
My views.py是:
def search(request):
feature_list = Volcano.objects.all()
feature_filter = VolcanoFilter(request.GET, queryset = feature_list)
return render(request, 'app/search_list.html', {'filter' : feature_filter, 'feature_type': feature_type})
在我的应用程序中,会出现一个可能的火山口数量的下拉列表,但搜索不会返回正常的结果,因为火山信息.vd_inf_numcal、火山信息.vd_id和火山信息.vd_id之间没有关系
它甚至说选择一个有效的选择。该选择不是可用的选择之一
我的问题是如何使用django_过滤器创建此链接?
我想我应该在课堂上写些方法,但我完全不知道怎么做
如果有人知道答案,我会非常感激 一般来说,您需要回答两个问题: 我们查询的是哪个字段&需要生成哪些查询/查找表达式。 我们应该使用什么类型的值进行筛选。 这些答案基本上是您的.filter调用的左侧和右侧 在本例中,您将过滤火山信息关系vd_inf_vd_id的反面,与火山的火山口vd_inf_numcal的数量相对应。此外,您需要精确匹配 对于这些值,您需要一组包含整数的选项 将查看DB列并根据列值生成选项。但是,缺点是这些选择不会包含任何缺失的值,这些值在渲染时看起来很奇怪。您可以调整此字段,也可以使用普通的ChoiceFilter,自己生成值 def num_火山口选择: 获取最大数量的火山口 max\u count=VolcanoInformation.objects.aggregateresult=max'vd\u inf\u numcal'['result'] 为“选择”下拉列表生成两个元组的列表,从0到最大计数 e、 g[0,0,1,1,2,2,…] 返回ziprangemax_计数,rangemax_计数 类过滤器Jango_过滤器。过滤器集: 名称=。。。 num_calderas=django_filters.ChoiceFilter 相关字段遍历注意连接“\uu 字段\u name='vd\u inf\u vd\u id\uu vd\u inf\u numcal', 标签='火山口数量', 选择数=火山口选择数 类元: 模型=火山 字段=['name','num_calderas']
请注意,我还没有亲自测试上述代码,但它应该足够接近您开始使用。非常感谢!那正是我要找的!我不明白.过滤器是怎么工作的 对于其他属性,我所做的是以不同的方式生成选择。例如,如果我只想显示可用位置的列表,我将使用:
# Location attribute
loc = VolcanoInformation.objects.values_list('vd_inf_loc', flat=True)
vd_inf_loc = django_filters.ChoiceFilter(
field_name='vd_inf_vd_id__vd_inf_loc',
label='Geographic location',
choices=zip(loc, loc),
)