Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django unique_together not preventing duplicates

Tags:

python

django

I am clearly not understanding how to do this correctly, can someone set me straight. Here is the model:

class Team(models.Model):    teamID=models.CharField(max_length=255) #this will be generated on the iPad    name=models.CharField(max_length=255)    slug=models.SlugField(max_length=50)     teamNumber=models.CharField(max_length=30)    checkIn=models.DateTimeField(default=datetime.now())    totalScore=models.IntegerField(max_length=6)      class Meta:        unique_together = ("teamID", "name", "slug", "teamNumber", "totalScore") 

If I submit twice in a row it saves all of it. Yikes!!!

like image 256
jasongonzales Avatar asked Jan 13 '12 00:01

jasongonzales


People also ask

How do I avoid duplicates in Django?

Use the get_or_create() Method in Django When we create duplicate objects multiple times, this method helps us avoid creating them multiple times.

What is Django Unique_together?

unique_together may be deprecated in the future. This is a list of lists that must be unique when considered together. It's used in the Django admin and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement).


1 Answers

As aganders3 mentions the constraint is enforced at the database level; I assume though that you are using a database like SQLite that doesn't support this kind of constraint.

The reason that it all works as expected through the admin is that it is doing the uniqueness check itself (it doesn't rely strictly on the database to signal constraint violations).

You can switch to a database engine that supports this kind of uniqueness constraint (either MySQL or Postgres would work) or you could look at adding the check in using signals: http://djangosnippets.org/snippets/1628/

like image 100
Stefan Magnuson Avatar answered Oct 04 '22 04:10

Stefan Magnuson