django-postgres-composite-types
django-postgres-composite-types copied to clipboard
Implement lookups on values within composite types
It should be possible to do a lookup on a composite type:
Person.objects.filter(address__suburb="Preston")
+1
Hey, is there any active work being done on this, or is there any reference to how one will provide filtering in composite types.
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.
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}"'