Django的双重下划线 [英] Django's Double Underscore

查看:102
本文介绍了Django的双重下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,您可以进行以下数据库查询:

  Model.objects.filter(name__icontains ='bob' )

问题是:这是如何工作的?双引号是Django的东西还是Python的东西?这只是一个名为 name__icontains 的变量,还是某种属性访问语法?在前一种情况下, filter 方法如何解析变量名称,以确定您正在搜索 Model 表格 >

这是一个Django的事情,实现了一些Python的东西。



在Python中,您可以获取传递给函数或方法的关键字参数的字典: / p>

 >>> def func(* args,** kwargs):
... print(kwargs)
>>>> func(a = 1,b = 2)
{'a':1,'b':2}

从那里,它可以简单地遍历字典键并将它们分割在 __ 上,然后解释它。在这种情况下,它需要最后一部分,并将 icontains 解释为不区分大小写。


In Django, you can make database queries like the following:

Model.objects.filter(name__icontains = 'bob')

The question is: how is this working 'under the cover'? Is the double underscore a Django thing or a Python thing? Is this just a single variable named name__icontains, or is it some sort of attribute-access syntax? In the former case, how does the filter method parse the variable name to determine that you are searching the Model table for a name that contains somewhere the string bob?

解决方案

It's a Django thing, implemented with some Python things.

In Python, you can get a dictionary of the keyword arguments passed to a function or method:

>>> def func(*args, **kwargs):
...     print(kwargs)
>>> func(a=1, b=2)
{'a': 1, 'b': 2}

From there, it can simply iterate over the dictionary keys and split them on __, and then interpret it however it wants. In this case, it takes the last part and interprets icontains as case-insensitive contains.

这篇关于Django的双重下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆