Python 模型中的 Django 外键(用户)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34305805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
django foreignkey(user) in models
提问by deltaskelta
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()
采纳答案by Dean Christian Armada
I do not know the "settings.AUTH_USER_MODEL" approach but a well-known approach and commonly used is the "Auth.User" model. Something like this on your end.
我不知道“settings.AUTH_USER_MODEL”方法,但一种众所周知的方法和常用的方法是“Auth.User”模型。像这样的事情在你身边。
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()
回答by Andrew E
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()
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.
而不是
User
直接引用,你应该使用引用用户模型django.contrib.auth.get_user_model()
当您为用户模型定义外键或多对多关系时,您应该使用
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,
)
回答by Sérgio
the column "author_id" doesn't exist, looks like is the same problem from here : Django suffix ForeignKey field with _id, so to avoid this traceback you may use :
列“author_id”不存在,看起来与这里的问题相同:Django 后缀 ForeignKey 字段与 _id,因此为了避免这种回溯,您可以使用:
author = models.ForeignKey(User, db_column="user")
回答by Jermaine
If you created a custom User model, you would use setting.AUTH_USER_MODEL
, if not you can go ahead an use User model
如果您创建了自定义 User 模型,您将使用setting.AUTH_USER_MODEL
,否则您可以继续使用User model