alias51
alias51

Reputation: 8648

PostgreSQL psycopg2 error: there is no unique constraint / InvalidForeignKey

I have the following models:

class Contact(models.Model):
    email = models.EmailField()

class EventList(models.Model):
    event_contacts = models.ManyToManyField(Contact, through=EventMembership)

class EventMembership(models.Model):
    event_list = models.ForeignKey(EventList, null=True, on_delete=models.PROTECT)
    event_contact = models.ForeignKey(Contact, null=True, blank=False, on_delete=models.PROTECT)

However, when applying migrations for EventMembership on a completely clean database I get the following error:

psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "contacts_contact"

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('lists', '0001_initial'),
        ('contacts', '0002_auto_20200308_2253'),
    ]

    operations = [
       migrations.CreateModel(
            name='EventMembership',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('event_contact', apps.utils.django_multitenant.fields.TenantForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='contacts.Contact')),
                ('event_list', apps.utils.django_multitenant.fields.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='lists.EventList'))
                  ]
                ]

Table contacts_contact clearly has a unique constraint in id as the primary key.

What could be causing this error? / How do I debug this?

Upvotes: 0

Views: 846

Answers (1)

Andrei Osmolovskii
Andrei Osmolovskii

Reputation: 117

You just need to do it step by step. Now you are trying to create a foreign key relationship with a table that is not in the database yet. So comment everything out except for Contact model, apply migrations, then add EventList etc. If you are relying on the fact that Contact model goes first, well, it doesn't help in this case.

Upvotes: 0

Related Questions