[Solved]-How to avoid brackets in SQL around Django custom database function call?

9๐Ÿ‘

โœ…

Iโ€™ve managed to get (more or less) what you need using following:

from django.db.models.lookups import BuiltinLookup
from django.db.models.fields import Field

class Any(BuiltinLookup):
    lookup_name = 'any'

    def get_rhs_op(self, connection, rhs):
       return " = ANY(%s)" % (rhs,)

Field.register_lookup(Any)

and query:

Vehicle.objects.filter(make__any=F('dealer__make_list')).count()

as result:

SELECT COUNT(*) AS "__count" FROM "zz_vehicle"
  INNER JOIN "zz_dealer" ON ("zz_vehicle"."dealer_id" = "zz_dealer"."id")
    WHERE "zz_vehicle"."make"  = ANY(("zz_dealer"."make_list"))

btw. instead djorm_pgarray and TextArrayField you can use native django:

make_list = ArrayField(models.CharField(max_length=200), blank=True)

(to simplify your dependencies)

๐Ÿ‘คJerzyk

Leave a comment