django 动态查询,动态 增加 filter 字段
By:Roy.LiuLast updated:2012-08-01
在用DJANGO开发应用的时候,通常会涉及对多个字段进行查询,并得到结果。
但有时候,比如自定义查询时,字段并不是定死的,而是动态增加的。
比如有一个类:
我们的目标是做成一个动态的查询。这个时候需要用到 kwargs.
用这种方式,在Q object 方式下,是有问题的,要采用如下方式:
什么是 Q Object 方式,参考:
https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
但有时候,比如自定义查询时,字段并不是定死的,而是动态增加的。
比如有一个类:
class Entry( models.Model ):
user = models.CharField(max_length=64)
category = models.CharField(max_length=64 )
title = models.CharField( max_length = 64 )
entry_text = models.TextField()
deleted_datetime = models.DateTimeField()
我们的目标是做成一个动态的查询。这个时候需要用到 kwargs.
kwargs = {
# 动态查询的字段
}
# 选择deleted_datetime为空的记录
if exclude_deleted:
kwargs[ 'deleted_datetime__isnull' ] = True
# 选择特的category
if category is not None:
kwargs[ 'category' ] = category
# 特定的用户
if current_user_only:
kwargs[ 'user' ] = current_user
# 根据标题查询
if title_search_query != '':
kwargs[ 'title__icontains' ] = title_search_query
# 应用所有的查询
entries = Entry.objects.filter( **kwargs )
# 打印出所有的结果检查
print entries
用这种方式,在Q object 方式下,是有问题的,要采用如下方式:
kwargs = { 'deleted_datetime__isnull': True }
args = ( Q( title__icontains = 'Foo' ) | Q( title__icontains = 'Bar' ) )
entries = Entry.objects.filter( *args, **kwargs )
什么是 Q Object 方式,参考:
https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
From:一号门
Previous:python pil 验证码,汉字验证码
Next:mysql数据库备份恢复常用命令集合

COMMENTS