在Django中创建自定义字段查找 [英] Creating custom Field Lookups in Django

查看:187
本文介绍了在Django中创建自定义字段查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建自定义字段查找在Django?

How do you create custom field lookups in Django?

过滤查询集时,django提供了一组可用于查找的内容: __包含 __ iexact __ in 等等。我想能够为我的经理提供一个新的查找,所以例如有人可以说:

When filtering querysets, django provides a set of lookups that you can use: __contains, __iexact, __in, and so forth. I want to be able to provide a new lookup for my manager, so for instance, someone could say:

twentysomethings = Person.objects.filter(age__within5=25)

并返回所有 Person 对象,年龄在20到30之间。我需要将 QuerySet Manager 上课这样做吗?如何实现?

and get back all the Person objects with an age between 20 and 30. Do I need to subclass the QuerySet or Manager class to do this? How would it be implemented?

推荐答案

截至Django 1.7,有一种简单的方法来实现它。您的示例实际上与文档中的示例非常相似:

As of Django 1.7, there is a simple way to implement it. Your example is actually very similar to the one from the documentation:

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)

注册时,您可以使用 Field.register_lookup(AbsoluteValueLessThan)

这篇关于在Django中创建自定义字段查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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