简体   繁体   中英

django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table

I am having a problem with Django 2.2.7 and postgresql 12 using the command "python manage.py migrate".

When I execute it, the process fails with the following error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "clients_clients"

I understand that this error indicates that when a field is used as a foreing key in another table, this field must be unique.

My model clients in Django is:

class Clients(models.Model):
    name = models.CharField(max_length=60, unique=True)
    document_num = models.CharField(max_length=15)
    phone = models.CharField(max_length=15, blank=True)
    email = models.EmailField(max_length=30, blank=True)
    instagram = models.CharField(max_length=30, blank=True)
    address = models.TextField(max_length=100, blank=True)

The model with the foreing key to the field "name" of clients_clients is:

class Budgets(models.Model):
    date = models.DateField(error_messages={'null': "You must set a date"})
    title = models.CharField(max_length=50, unique=True)
    client = models.ForeignKey(Clients, null=True, on_delete=models.SET_NULL, to_field='name')
    price = models.DecimalField(default=0, decimal_places=2, max_digits=10)
    observations = models.TextField(max_length=200, blank=True)

As is shown above, the field "name" in model "Clients" is set as unique=True. But in spite of that, the error mentioned is shown.

Anyone can help me to understand why?

I could fix the problem.

The problem is as I copied my Django application from an existing installation to a new one, a lot of migration files exist in the app folders.

First, I had to delete all the files inside the "migrations" folders in any app of my Django project (taking care of not delete the init .py file).

Then I ran again the commands: python manage.py makemigrations

and

python manage.py migrate

Now, everything works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM