在django过滤器中使用非模型django字段



我有一个变量'cptCodeTBX',它不存在于django模型中的字段。我需要在"cptCodeTBX"变量上应用过滤器。大致相当于

cptCodeTBX = '00622'
select * from cpt where cpt.code like cptCodeTBX or cptCodeTBX is != ''

在。net实体框架中我们可以通过

b = cptContext.CPTs.AsNoTracking().Where(
a =>
(String.IsNullOrEmpty(cptCodeTBX) || a.Code.StartsWith(cptCodeTBX))

这可能不是性能最好的解决方案,但我能够让它工作。

步骤1:阅读Django Filter文档

https://django-filter.readthedocs.io/en/stable/index.html

步骤2:在Django模型中添加一个名为cptCodeTBX的属性。

from django.db import models
class MyModel(models.Model):
field = models.CharField(max_length=60)
@property
def cptCodeTBX(self):
"""
Does all the code tbx cpt stuff, can do whatever you want.
"""
cptCodeTBX = 2323 #whatever value you want     
return cptCodeTBX

步骤3:添加Django过滤器

import django_filters    
class CptCodeTBXFilter(django_filters.FilterSet):
"""
Filter that will do all the magic, value comes from url query params.
Replace filters.NumberFilter with any filter you want like
filters.RangeFilter.
"""
cptCodeTBX = django_filters.NumberFilter(
field_name="cptCodeTBX",
method="filter_cptCodeTBX",
label="Cpt Code TBX",
)
def filter_cptCodeTBX(self, queryset, name, value):
objects_ids = [
obj.pk for obj in MyModel.objects.all() if obj.cptCodeTBX == value
]
if objects_ids:
queryset = MyModel.objects.filter(pk__in=objects_ids)
else:
queryset = MyModel.objects.none()
return queryset

步骤4:将值作为查询参数通过url传递。

http://example.com/?cptCodeTBX=00622

最新更新