Debojit Kaushik
Debojit Kaushik

Reputation: 103

Foreign Key constraint error In Django

I am extending the Abstract user model in Django and it's not letting me migrate throwing an error related to the foreign key.

from django.db import models
from django.contrib.auth.models import AbstractUser
import uuid

#Database model for Users.
class User(AbstractUser):
'''
    Abstract user model inherited containing all basic fields such as:
    first and last name, username, email, password etc. Abstract User fields. 
'''
    user_id = models.UUIDField(
        primary_key = True, 
        default = uuid.uuid4, 
        editable = False
        )
    is_owner = models.BooleanField(
    default = False
    )



    class Meta:
        db_table = 'Users'

    def __str__(self):
         self.constructLabel(
            self.first_name, 
            self.last_name,
            self.user_id
        )

The error : django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')

From the database error is:

2017-04-09 20:33:07 0x7f3440171700 Error in foreign key constraint of table shipapp/#sql-3c9_33:
 FOREIGN KEY (`user_id`) REFERENCES `users_user` (`user_id`):
Cannot resolve table name close to:
 (`user_id`)

Can anybody who has faced this before help me out? I have been out of touch since Django 1.8.5 was released. :(

Upvotes: 1

Views: 1359

Answers (1)

Debojit Kaushik
Debojit Kaushik

Reputation: 103

I solved my problem at least although it's not a recommended way to solve this although the solution might be specific to my problem. As I had just started making the models I could afford to re-initialise the whole project and copy the models and make migrations again. The problem was I think in the initial migration files that were created and after repeatedly deleting and recreating the files the error still arose from those initial files.

The lesson to be learned from this and the things I did wrong was:

Mistakes :

  1. I made multiple models based on the E-R diagram I had made concurrently.
  2. I did not migrate while I made all of them.
  3. Made all of the relations at the same time.
  4. Tried to migrate them at once and there arose a race condition of a kind. Every relation was attempted while making the model. I read somewhere where a guy had quoted "You can't eat the pastry while still keeping it with yourself."

What I should have done:

  1. Made the models one by one.
  2. Migrated the models keeping them atomic ie: without the relations between them. Keep only non-relation fields.
  3. After migrating the models, write out the relations between the models.
  4. Then migrate the models with the relations between them.

Upvotes: 1

Related Questions