Django postgres conditional constraint

I'm trying to set a conditional unique limiter for one of the model fields (a column on db-perspectives) relative to another logical field, but I can not find a way to do this.

I am creating a web-management tool that helps / controls attendance based on numbered cards while they are still in the store. My main goal is to prevent my user from storing a card number while that number is still active (aka Boolean field) with another custumer. <w> Something like this on models.py:

    class Cards(models.Model):
         card_number = models.PositiveIntegerField("""{{RESTRICTION NEEDED}}""")
         card_date = models.DateTimeField(auto_now=False, auto_now_add=True)
         custumer = models.ForeignKey(Customer)
         status = models.BooleanField(default=False)

maybe something like this will work directly on postgres, haven't tried it yet

CREATE UNIQUE INDEX card_number_ind ON Cards (card_number) WHERE (status is False);

Is there any way to do this directly with Django? I mean to set a conditional unique limiter relative to the Boolean field (state) on Django?

TIA
Obs. This is my first question ever on stackoverflow, feel free to criticize the style.

+4
source share
1 answer

Django does not support defining conditional constraints in models.py, however you can create a migration to add such a constraint.

Start by creating an empty migration

./manage.py makemigrations appname --empty

This will create an empty migration file. Then you will want to add your custom restriction to the migration

class Migration(migrations.Migration):

    ... 

    operations = [
        migrations.RunSQL('create unique index card_number_ind on cards (card_number) where (status is false)'),
    ]
+2
source

Source: https://habr.com/ru/post/1627206/


All Articles