Opened 3 years ago

Last modified 3 years ago

#33192 closed Bug

It is not possible to use a custom lookup/transorm in a CheckConstraint — at Version 2

Reported by: Fabien MICHEL Owned by: nobody
Component: Database layer (models, ORM) Version: 3.1
Severity: Normal Keywords: lookup, transform, CheckContraint, migrate
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Fabien MICHEL)

Using a custom lookup or transform in a CheckContraint make migrate command fail.

class MonthLastDay(Transform):
    lookup_name = "month_last_day"
    output_field = DateField()
    template = "(DATE_TRUNC('month', %(expressions)s) + (interval '1 month - 1 day'))::date"

DateField.register_lookup(MonthLastDay)

class MyModel(models.Model):
    class Meta:
        constraints = [
            CheckConstraint(check=Q(date__month_last_day__gte=F("period_start")), name="date_month_end_after_period_start"),
        ]

   date = models.DateField()
   period_start = models.DateField()

django makemigrations command does not indicate any issue with this and make use of month_last_day lookup as if it know about it.

Migration command for this contraint:

migrations.AddConstraint(
    model_name='mymodel',
    constraint=models.CheckConstraint(
        check=models.Q(
            ('date__month_last_day__gte', django.db.models.expressions.F('period_start'))
        ), 
        name='project_period_charge_type_task_month_budget_month_in_period'),
),

django migrate command fail indicating that date__month_last_day join is not possible

django.core.exceptions.FieldError: Joined field references are not permitted in this query

I'm not sure what could be done. May be the documentation should warn to not use custom lookup/transform in CheckContraint.

Change History (2)

comment:1 by Fabien MICHEL, 3 years ago

Description: modified (diff)

comment:2 by Fabien MICHEL, 3 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top