0

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!

1
  • Can you show your models please? Commented Dec 1, 2020 at 9:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this seems to be working properly now. Curious part is that I already had the unique=True in both fields and made the proper migrations.
1

You can accomplish this by adding unique=True to your model fields.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.