gpt4 book ai didi

python - MySQL 和 Django 外键到用户模型

转载 作者:行者123 更新时间:2023-11-30 22:24:09 25 4
gpt4 key购买 nike

我用来自 django 的用户模型的所有者外键制作了这个模型。

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


class Publicacion(models.Model):
titulo = models.CharField(max_length=120)
owner = models.ForeignKey(User)
contenido = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
fechahora = models.DateTimeField(auto_now=False, auto_now_add=True)

class Meta:
ordering = ['fechahora']
verbose_name_plural = 'Publicaciones'

def __unicode__(self):
return '%s %s' % (self.titulo, self.contenido)

但是当我进行迁移时,我得到了这个错误:“django.db.utils.OperationalError: (1072, 'Key column 'owner_id' doesn't exist in table").

我还应该做什么?

已安装的应用

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'usuarios',
'publicaciones',
)

最佳答案

你必须有一个列来存储你的mysql数据库中的外键

模型中的字段必须类似于:

 owner = models.ForeignKey('auth.User')

数据库表中的列必须是:

owner_id      INT(11)

我不知道为什么,但 django 将“_id”添加到数据库列名。

另外,如果你不想要后缀为“_id”的数据库列名,你可以在模型字段中添加:

db_column='owner'

所以一定是:

 owner = models.ForeignKey('auth.User',db_column='owner')

但请记住在您的数据库中创建该列。

关于python - MySQL 和 Django 外键到用户模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35803538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com