[英]django foreignkey(user) in models
I read the docs and this post... Django - Foreign Key to User model 我阅读了文档和这篇文章...... Django - 用户模型的外键
I followed what it said and I still cannot get it to work. 我按照它所说的,我仍然无法让它工作。 When I try to run the migrations I get this error in the traceback...
当我尝试运行迁移时,我在追溯中得到了这个错误...
django.db.utils.ProgrammingError: column "author_id" cannot be cast automatically to type integer
HINT: You might need to specify "USING author_id::integer".
I just don't know how to go about fixing that error. 我只是不知道如何解决这个错误。
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BlogCategory(models.Model):
'''model for categories'''
title = models.CharField(max_length=30)
description = models.CharField(max_length=100)
class BlogPost(models.Model):
'''a model for a blog post'''
author = models.ForeignKey(User)
date = models.DateField()
title = models.CharField(max_length=100)
post = models.TextField()
Don't use the User
model directly. 请勿直接使用
User
模型。
From the documentation 从文档中
Instead of referring to
User
directly, you should reference the user model usingdjango.contrib.auth.get_user_model()
您应该使用
django.contrib.auth.get_user_model()
来引用用户模型,而不是直接引用User
When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the
AUTH_USER_MODEL
setting.为用户模型定义外键或多对多关系时,应使用
AUTH_USER_MODEL
设置指定自定义模型。
Example: 例:
from django.conf import settings
from django.db import models
class Article(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
If you created a custom User model, you would use setting.AUTH_USER_MODEL
, if not you can go ahead an use User model
如果你创建了一个自定义用户模型,你将使用
setting.AUTH_USER_MODEL
,如果没有你可以继续使用User model
列“author_id”不存在,从这里看起来是同样的问题: 带有_id的Django后缀ForeignKey字段 ,所以为了避免这种回溯你可以使用:
author = models.ForeignKey(User, db_column="user")
I do not know the "settings.AUTH_USER_MODEL" approach but a well-known approach and commonly used is the "Auth.User" model. 我不知道“settings.AUTH_USER_MODEL”方法,但一种众所周知的方法和常用的是“Auth.User”模型。 Something like this on your end.
你最喜欢这样的东西。
from django.contrib.auth.models import User
class BlogPost(models.Model):
'''a model for a blog post'''
author = models.ForeignKey(User)
date = models.DateField()
title = models.CharField(max_length=100)
post = models.TextField()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.