#36981: Add PostgreSQL num_nonnulls (code provided)
-------------------------------------+-------------------------------------
Reporter: Robin Christ | Type: New
| feature
Status: new | Component: Database
| layer (models, ORM)
Version: 6.0 | Severity: Normal
Keywords: | Triage Stage:
| Unreviewed
Has patch: 1 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 1 | UI/UX: 0
-------------------------------------+-------------------------------------
I recently implemented "anyOf" / "tagged union" fields. I added
specialized CheckConstraints using num_nonnulls
The code looks like this:
{{{
class NumNonNulls(Func):
"""
Wraps PostgreSQL `num_nonnulls`.
Returns the number of non-null arguments as an integer. Can be used
with
`F()` references to model fields (including e.g. OneToOne)
relationships.
Example::
NumNonNulls(F("one_to_one_rel_1"), F("one_to_one_rel_1"))
-> SQL: num_nonnulls("one_to_one_rel_1_id",
"one_to_one_rel_2_id")
"""
function = "num_nonnulls"
def __init__(self, *expressions: object, **extra) -> None:
super().__init__(*expressions, output_field=IntegerField(),
**extra)
class NumNonNullsEq(Func):
"""
Renders ``num_nonnulls(<args>) = <n>`` as a boolean expression.
Suitable for use as the `condition` of a `CheckConstraint`.
Parameters
----------
*expressions:
The expressions (e.g. `F()` expressions) to pass to
`num_nonnulls`.
count:
The value or expression the result must equal.
Example::
NumNonNullsEq(F("one_to_one_rel_1"), F("one_to_one_rel_2"),
count=1)
-> SQL: num_nonnulls("one_to_one_rel_1_id", "one_to_one_rel_2_id")
= 1
"""
arg_joiner = " = "
template = "%(expressions)s"
def __init__(self, *expressions: object, count: object, **extra) ->
None:
if not expressions:
raise ValueError("NumNonNullsEq() requires at least one
expression.")
super().__init__(
NumNonNulls(*expressions),
count,
output_field=BooleanField(),
)
}}}
Is there any interest from Django's side in this?
--
Ticket URL: <https://code.djangoproject.com/ticket/36981>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion visit
https://groups.google.com/d/msgid/django-updates/0107019ce18943fe-92bd3996-c030-498a-8e14-a0ba1acc7e51-000000%40eu-central-1.amazonses.com.