django-postgres-composite-types icon indicating copy to clipboard operation
django-postgres-composite-types copied to clipboard

Implement lookups on values within composite types

Open danni opened this issue 8 years ago • 3 comments

It should be possible to do a lookup on a composite type:

Person.objects.filter(address__suburb="Preston")

danni avatar Jun 01 '16 00:06 danni

+1

raiviskrumins avatar Jul 25 '16 10:07 raiviskrumins

Hey, is there any active work being done on this, or is there any reference to how one will provide filtering in composite types.

Dipenbhatt03 avatar Nov 12 '21 12:11 Dipenbhatt03

No, I've worked on this package on an as-needs basis only. So unfortunately if you want this feature you're going to have to work out how to make it work. It is possible to filter on the whole tuple (e.g. using structs as structured keys).

If you wanted a quick solution, you could write a lookup function (class Lookup/register_lookup) for the generated field type.

You could also consider Postgres' JSON field, the jsonpath support is quite robust now.

danni avatar Nov 13 '21 02:11 danni

Hi all, feedback welcome on PR linked above if you're still interested in this and have a chance to try it out.

Or, if you prefer, the work-around for a single case I was using prior to working that up to cover all members was:

class SomeType(CompositeType):
    member = # ...
    
SomeField = SomeType.Field

@SomeField.register_lookup
class SomeMemberLookup(django.db.models.Transform):
    lookup_name = "member"
    col_name = next(
        filter(
            lambda af: af[1].attname == "member",
            SomeType._meta.fields,  # pylint: disable=protected-access
        )
    )[1].column

    arity = 1
    template = f'(%(expressions)s)."{col_name}"'

OJFord avatar Mar 17 '23 16:03 OJFord