M
M
Maxim2018-09-06 09:29:18
Django
Maxim, 2018-09-06 09:29:18

How to make a many-to-one relationship in the base User model?

Good afternoon, I'm trying to make a connection with the standard User model in django. Used both sqlite3 and mysql.

from django.db import models
from django.conf import settings
from django.contrib.auth.models import User

class Post(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    like = models.BigIntegerField(default=0)
    text = models.TextField(max_length=1000, blank=True, default='')

Mistake
-> post = Post.objects.create(owner=user, text=text)
(Pdb) n
django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (`starnavi`.`post_post`, CONSTRAINT `post_post_owner_id_d5aa4d97_fk_accounts_user_id`
 FOREIGN KEY (`owner_id`) REFERENCES `accounts_user` (`id`))')
> /home/maxim/dev/projects/starnavi/app/app/post/serializers.py(61)validate()
-> post = Post.objects.create(owner=user, text=text)
(Pdb)

1. It is impossible to link the base model with others?
2. How can it be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Danny Belchenko, 2018-09-06
@belchenko

I think you should bind not to the model, but to a specific key, for example User.id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question