Tuesday, February 18, 2020

Re: Model uniqueness constraint with date extraction

Hello Thierry,

Django doesn't support support constraints on lookups/expressions but there's ungoing work to do so[0].

In the mean time you'll have to rely on a `RunSQL` operation  in your migrations to create the constraint.

Cheers,
Simon

[0] https://code.djangoproject.com/ticket/30916

Le mardi 18 février 2020 09:32:19 UTC-5, Thierry Backes a écrit :

Hey,

 

I have a model which has a date and a foreign key field. I want a uniqueness constraint that each fk can only be used once per month, so Unique(date__year, date__month, fk). However, when I use this in my model's metadata:

 

models.UniqueConstraint(fields=['date__year', 'date__month', 'category'], name='date_month_cat_unique')

 

I get an error that the date__year field doesn't exist. This is a bit strange because I use this syntax throughout my app and I also know that such constraints are supported by Postgres:

 

create unique index year_month_uq

  on foo

  ( extract(year from mydate),

    extract(month from mydate)

  ) ;

 

As per https://dba.stackexchange.com/questions/210736/postgresql-enforcing-unique-constraint-on-date-column-parts

 

What am I doing wrong here? I'm using Django 3 and Postgres.

 

Thanks

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/030dbd7e-b4bd-4905-9a59-cbb61d12132e%40googlegroups.com.

No comments:

Post a Comment