Search code examples
pythondjangosqlitemodels

Django UNIQUE constraint failed with OneToOneField while migrate in Django User Model


In database I have already registered 4 persons but they were registered when model hasn't had relation attributes yet. When I added them I got this model:

class Person(User):
    type = models.BooleanField()
    avatar = models.ImageField(blank=True)
    second_name = models.CharField(max_length=30, blank=True, default='')
    birthday = models.DateField(blank=True, default=None)  
    country = models.CharField(max_length=30, blank=True, default='')
    city = models.CharField(max_length=30, blank=True, default='')
    school = models.CharField(max_length=60, blank=True, default='')
    university = models.CharField(max_length=60, blank=True, default='')
    work_place = models.CharField(max_length=60, blank=True, default='')
    profession = models.CharField(max_length=60, blank=True, default='')
    phone = models.CharField(max_length=30, blank=True, default='')
    about = models.TextField(blank=True, default='')
    latitude = models.FloatField(blank=True, default=-1)
    longitude = models.FloatField(blank=True, default=-1)

    friends = models.ForeignKey(
        'self',
        related_name='+',
    )

    black_list = models.ForeignKey(
        'self',
        related_name='+',
    )

    dialogues = models.ManyToManyField(
        'dialogues.Dialogue',
    )

    news = models.OneToOneField(
        'news.NewsList',
    )

    wall = models.OneToOneField(
        'blogs.Blog',
    )

But now when this model migrates I have the error: django.db.utils.IntegrityError: UNIQUE constraint failed: persons_person.wall_id.


Solution

  • You should change the relation with Blog model, as one Person can write more than 1 blog, hence its a 1-M relation. So in Blog model you should define a ForeignKey to Person model.

    person = models.ForeignKey(
            'person.Person',
            related_name='walls'    
        )
    

    And wall field will be removed from Person model, but from person objects you will be able to access blogs using related name walls.

    If your have a necessity of having Person to Blog as 1-1 relation, then your will have to remove records from database which don't follow this constraint.