本文介绍了在Django中,如何使用动态字段查找过滤QuerySet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个类:

 从django.db导入模型

class Person(models。模型):
name = models.CharField(max_length = 20)

如果是这样,要有一个基于动态参数过滤的QuerySet?例如:

 #而不是:
Person.objects.filter(name__startswith ='B')
#...和:
Person.objects.filter(name__endswith ='B')

#...有一些方法,给出:
filter_by ='{ 0} __ {1}'。格式('name','startswith')
filter_value ='B'

#...你可以运行相当于此?
Person.objects.filter(filter_by = filter_value)
#...将抛出异常,因为`filter_by`不是
#一个Person属性。

帮助非常感激和欣赏谢谢你提前。

解决方案

Python的参数扩展可能用于解决这个问题:

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

Person.objects.filter(** kwargs)

这是一个非常常见和有用的Python成语。


Given a class:

from django.db import models

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

Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example:

 # 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`.

Help is much appreciated & thank you in advance.

解决方案

Python's argument expansion may be used to solve this problem:

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

Person.objects.filter(**kwargs)

This is a very common and useful Python idiom.

这篇关于在Django中,如何使用动态字段查找过滤QuerySet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 21:21