gregory_000
gregory_000

Reputation: 35

How to set unique_together for a user field

I am learning Django. I am creating app where I have a model Employer. In a database, I want to keep only one record for fields user and website.

I tried to use unique_together in my model but during migration I got the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: employer_employer.user_id, employer_employer.website

Can you please advice me what is a problem? Maybe this is not a good way how to do it? Thanks!

class Employer(models.Model):
    USER = settings.AUTH_USER_MODEL

    user = models.ForeignKey(USER, default=1, on_delete=models.CASCADE)
    company_name = models.CharField(max_length=200)
    company_size = models.IntegerField(default=0)
    website = models.CharField(max_length=200)

    class Meta:
        unique_together = ('user', 'website')

Upvotes: 1

Views: 45

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

I tried to use unique_together in my model but during migration I got the following error: django.db.utils.IntegrityError: UNIQUE constraint failed: employer_employer.user_id, employer_employer.website

This means the migration is perfectly fine. It means there is already data in the database that violates the constraint, so you will first need to go through the fact that there are Employer objects in the database with the same user and the same website.

You can find such Users effectively with:

from django.db.models import Count

Employee.objects.values('user', 'website').annotate(count=Count('pk')).filter(
    count__gt=1
)

then you will have to fix these Employer records.


Note: As the documentation on unique_together [Django-doc] says, the unique_together constraint will likely become deprecated. The documentation advises to use the UniqueConstraint [Django-doc] from Django's constraint framework.

Upvotes: 1

Related Questions