Skip to main content
 首页 » 编程设计

python之django如何在filter中实现双下划线

2024年08月21日3398°冷暖

我注意到 Django 使用 double under score 在 Model.objects.filter 实例中定义一个 lookup。

例如:

Room.objects.filter(width__lte = 10)

它是如何工作的?我怎样才能像 Django 一样创建自己的函数并知道 width__lte 实际上是分开的 width 和 小于或等于 10。

请您参考如下方法:

Django 1.10 Documentation关于自定义查找:

Taking a closer look at the implementation, the first required attribute is lookup_name. This allows the ORM to understand how to interpret name__ne and use NotEqual to generate the SQL. By convention, these names are always lowercase strings containing only letters, but the only hard requirement is that it must not contain the string __.

来自另一个来源:

Lookups: Those are basically “a condition in the query’s WHERE clause”. Examples in django are lt, gt, gte, contains and so. To create a custom lookup, you subclass models.Lookup. You set the lookup_name and you implement the .as_sql() method. Afterwards you register it for the various Field types for which it is valid.

您可以阅读更多 here .

我也引用 this answer :

from django.db.models import Lookup 
 
class AbsoluteValueLessThan(Lookup): 
    lookup_name = 'lt' 
 
    def as_sql(self, qn, connection): 
        lhs, lhs_params = qn.compile(self.lhs.lhs) 
        rhs, rhs_params = self.process_rhs(qn, connection) 
        params = lhs_params + rhs_params + lhs_params + rhs_params 
        return '%s < %s AND %s > -%s' % (lhs, rhs, lhs, rhs), params 
 
AbsoluteValue.register_lookup(AbsoluteValueLessThan) 

While registering, you can just use Field.register_lookup(AbsoluteValueLessThan) instead.

从 stackoverflow 本身我得到了 django 双下划线 __ 的意思。 Have a look here .