Reputation: 15
Here is my problem,
I want to create an school administration site so I need to register the student data.
The students have two fields that need to be unique,
For example:
- Student A: 'enrollment_id: 123', 'other_field: ABC'
- Student B: 'enrollment_id: 234', 'other_field: CDE'
Those two fields can't have the same values. If I already have an student with ABC in the 'other_field' and I want to register an student with the same value, the app shouldn't allow that.
I'm using Django 3.1.1 and so far I have already tried UniqueTogether
and UniqueConstraint(fields = ['enrollment_id', 'other_field'], name='some_name')
in my Student Model and as PK I have the enrollment_id.
But that doesn't work. I can still register the same value in other_field
if enrollment_id
is different.
I need to mention that I'm using SQLITE
to test the app before migrating the DB to another Engine.
Also I'm using CBV to create the forms. Thank you very much, any help is appreciated!
Upvotes: 0
Views: 1517
Reputation: 169407
An unique together constraint is equivalent to an unique constraint with two (or more) fields.
You'll need separate unique constraints with one field each if you want to ensure the table ever only has one existence of a given value in a given field.
You can do that with two UniqueConstraint()
s, or by setting unique=True
on the model field.
Upvotes: 2
Reputation: 127
You can accomplish this by adding unique=True
to your model fields.
Upvotes: 1