一尘不染

在Django中,如何使用动态字段查找过滤QuerySet?

django

给定一堂课:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=20)

是否有可能(如果有的话)拥有一个基于动态参数进行过滤的QuerySet?例如:

 # Instead of:
 Person.objects.filter(name__startswith='B')
 # ... and:
 Person.objects.filter(name__endswith='B')

 # ... is there some way, given:
 filter_by = '{0}__{1}'.format('name', 'startswith')
 filter_value = 'B'

 # ... that you can run the equivalent of this?
 Person.objects.filter(filter_by=filter_value)
 # ... which will throw an exception, since `filter_by` is not
 # an attribute of `Person`.

阅读 511

收藏
2020-03-26

共1个答案

一尘不染

Python的参数扩展可用于解决此问题:

kwargs = {
    '{0}__{1}'.format('name', 'startswith'): 'A',
    '{0}__{1}'.format('name', 'endswith'): 'Z'
}

Person.objects.filter(**kwargs)

这是一个非常常见且有用的Python习惯用法。

2020-03-26