Creating custom Field Lookups in Django

前端 未结 4 881
悲&欢浪女
悲&欢浪女 2020-12-30 07:48

How do you create custom field lookups in Django?

When filtering querysets, django provides a set of lookups that you can use: __contains, __iexa

4条回答
  •  萌比男神i
    2020-12-30 08:34

    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)
    

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

提交回复
热议问题