【问题标题】:Creating a foreign key for user from one app to another in Django在 Django 中为用户从一个应用程序创建一个外键到另一个应用程序
【发布时间】:2017-11-04 19:13:49
【问题描述】:

我想在我的任务 models.py 中为另一个名为 UserProfile 的表创建一个用户外键。我希望将任务与用户相关联,因此当我去查询它并将其显示在个人资料页面中时,我看不到其他人的。但是,当我尝试这样做时,我得到了这个错误:

这是我的 tasks.model.py

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

class Task(models.Model):
    task_name = models.CharField(max_length=140, unique=True)
    owner = models.ForeignKey('user')
    description = models.CharField(max_length=140)
    create_date = models.DateField()
    completed = models.BooleanField()
    private = models.BooleanField()

    def __unicode__(self):  # Tell it to return as a unicode string (The name of the to-do item) rather than just Object.
        return self.name

这是我的 useraccounts.models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, default='')
    username = models.CharField(max_length=14, default='')
    birth_date = models.DateField(null=True, default = '2000-01-01', blank=True)
    email = models.EmailField(null=True, default='')

【问题讨论】:

  • 请不要发布截图。写下你的代码示例。毕竟它只是几行而已。
  • 我添加了代码。
  • 请对错误部分也这样做。

标签: django django-models foreign-keys


【解决方案1】:

在您的课程Task 中,您可以这样定义外键:

owner = models.ForeignKey('user')

这需要在同一个应用程序中有一个名为 user 的类。而你没有它。
因为您想从另一个应用程序建立与模型的关系,所以您必须使用以下模式app_label.Model。在您的情况下,它应该如下所示:

owner = models.ForeignKey('useraccounts.UserProfile')

【讨论】:

  • 我试过这个,但是当我在管理页面中添加一个东西时,我收到了这个错误:OperationalError at /admin/buyer/restaurant/add/ table Buyer_restaurant has no column named store_id
  • 现在我解决了,我的问题在哪里,我忘了进行迁移。
猜你喜欢
  • 2010-09-24
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 2018-03-24
  • 2014-08-26
  • 1970-01-01
相关资源
最近更新 更多