Django——当搜索模型对象的属性是一个可变的动态字段
场景:
准备做一个供前端搜索的功能,但是搜索的字段是指定的,可选项是数据库中该字段有的,因为这样的去重获取字段可选项,逻辑都是一样的,所以可以在一个方法里面写,也就出现了Model.objects.filter搜索的是一个动态可变的字段
思路:
后来在django.shortcuts.get_object_or_404方法里面获得了启发
def get_object_or_404(klass, *args, **kwargs): queryset = _get_queryset(klass) if not hasattr(queryset, 'get'): klass__name = klass.__name__ if isinstance(klass, type) else klass.__class__.__name__ raise ValueError( "First argument to get_object_or_404() must be a Model, Manager, " "or QuerySet, not '%s'." % klass__name ) try: return queryset.get(*args, **kwargs) except queryset.model.DoesNotExist: raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
解决办法:
FutureCargoModel.objects.filter(**{'product': 1}) Out[28]: <QuerySet [<FutureCargoModel: SEGU6222004>, <FutureCargoModel: HFVBORE>]>
FutureCargoModel.objects.filter(**{'product__value': '阿尔法'}) Out[29]: <QuerySet [<FutureCargoModel: SEGU6222004>, <FutureCargoModel: HFVBORE>]>
field = 'product' FutureCargoModel.objects.filter(**{field: 1}) Out[31]: <QuerySet [<FutureCargoModel: SEGU6222004>, <FutureCargoModel: HFVBORE>]> FutureCargoModel.objects.filter(**{f'{field}__value': '阿尔法'}) Out[32]: <QuerySet [<FutureCargoModel: SEGU6222004>, <FutureCargoModel: HFVBORE>]>
这样就达到了动态筛选
就很nice~