简体   繁体   English

在Django查询比较中使用变量而不是字段名称

[英]Using variable instead of field name in Django query comparions

Let say I have the following query: 假设我有以下查询:

query_result = Mymodel.objects.values('price').filter(price__gte=0)

If I want to generalize the query and put it in a function I could replace 'price' with a variable: 如果我想概括查询并将其放入函数中,我可以用变量替换'price'

def price_query(column_name):
    query_result = Mymodel.objects.values(column_name).filter(column_name__gte=0)
    return query_result 

price_query('price')

The first replacement of 'price' with column_name works fine but how do I use the comparison __gte with a variable instead of the field name. 使用column_name第一次替换'price'工作正常,但如何将__gte与变量而不是字段名称一起使用。

Any help is much appreciated. 任何帮助深表感谢。

You can unpack dictionary to provide keyword arguments: 您可以解压缩字典以提供关键字参数:

def price_query(column_name):
    filter_kwargs = {
        "{}__gte".format(column_name): 0
    }
    query_result = Mymodel.objects.values(column_name).filter(**filter_kwargs)
return query_result

Long story short, you cannot do this. 长话短说,你不能这样做。

Querysets are limited to model fields, which are the column names as you said. 查询集仅限于模型字段,这是您所说的列名称。 In fact, they operate only in database-layer, where your variables are not existent. 实际上,它们仅在数据库层中运行,其中您的变量不存在。

You will have to follow another filtering approach in order to include variables. 您必须遵循另一种过滤方法才能包含变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM