【问题标题】:foreignkey (user) in models模型中的外键(用户)
【发布时间】:2016-03-22 05:20:13
【问题描述】:

我阅读了文档和这篇文章...Django - Foreign Key to User model

我按照它所说的去做,但我仍然无法让它工作。当我尝试运行迁移时,我在回溯中收到此错误...

django.db.utils.ProgrammingError: column "author_id" cannot be cast automatically to type integer
HINT:  You might need to specify "USING author_id::integer".

我只是不知道如何解决这个错误。

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()

【问题讨论】:

  • 您使用的是默认用户模型吗?请包含相关的迁移文件

标签: python django django-models foreign-keys


【解决方案1】:

不要直接使用User 模型。

来自the documentation

不要直接引用User,而应该引用用户 模型使用django.contrib.auth.get_user_model()

当您为用户模型定义外键或多对多关系时,您应该使用AUTH_USER_MODEL 设置指定自定义模型。

例子:

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,
    )

【讨论】:

  • 在使用这个答案时让我感到困惑的是我是否需要在settings.py 中定义AUTH_USER_MODEL 设置。文档说没有必要 - This method will return the currently active user model – the custom user model if one is specified, or User otherwise.
  • documentation 声明:“Django 允许您通过为 AUTH_USER_MODEL 设置提供值来覆盖默认用户模型”。基本上:如果你提供了一个自定义的User模型,你必须提供AUTH_USER_MODEL设置。
【解决方案2】:

如果您创建了自定义用户模型,您将使用setting.AUTH_USER_MODEL,否则您可以继续使用User model

Referencing Django User model

【讨论】:

    【解决方案3】:

    “author_id”列不存在,从这里看起来是同样的问题:Django suffix ForeignKey field with _id,所以为了避免这种回溯,您可以使用:

    author = models.ForeignKey(User, db_column="user")
    

    【讨论】:

      【解决方案4】:

      我不知道“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()
      

      【讨论】:

      • 我在查找它并以其他方式执行之前尝试过。我得到同样的错误
      • 如果您没有覆盖AUTH_USER_MODEL setting,您所指的模型默认的
      • docs.djangoproject.com/en/1.9/topics/auth/customizing/…,正如链接所说的“AUTH_USER_MODEL”应该是某个应用程序的用户模型,你这样做了吗?或者您可能想提供其他额外的详细信息,例如您的 AUTH_USER_MODEL 的值
      • 我还没有为该类定义用户模型。有没有办法让它成为我数据库中所有用户的外键?
      • from django.contrib.auth.models import User author = models.ForeignKey(User) 是我为你得到的最佳答案,因为这是我一直使用的
      猜你喜欢
      • 2011-11-10
      • 2015-01-16
      • 2018-06-02
      • 2014-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      相关资源
      最近更新 更多