E
E
Egor Vavilov2020-03-02 19:43:34
Django
Egor Vavilov, 2020-03-02 19:43:34

How to fix FOREIGN KEY constraint failed error?

There are two models

class User(models.Model):
    username = models.CharField(max_length=50)
    email = models.CharField(max_length=100)
    password = models.CharField(max_length=50)

class Topic(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    creator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)


And the code for creating a new topic
Topic.objects.create(title=title, description=description, creator_id=user.id)


The only case where this code works is creator_id == 1. In all other cases I get an error
FOREIGN KEY constraint failed

Naturally, ideally, instead of unity, there should be
request.user.id


But it gives the same error. It got to the point that I tried to manually insert user IDs that exist into this field. Works only with 1.
I don’t understand what’s the matter. Tell me please.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question