【问题标题】:Django Relating Model to UserDjango 将模型与用户相关联
【发布时间】:2013-12-10 05:25:14
【问题描述】:

我想将我的网络应用程序中的 Note 模型与创建它的用户关联起来。我想这种关系应该是多对一的。这样我就可以按用户过滤数据。帮助我正确的代码,解释一下,你认为这是正确的方法,以便为每个用户提供单独的数据。我真的希望你对此发表意见。

class Note(models.Model): 
    title = models.CharField(max_length=200)
    body = models.TextField()
    cr_date = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(........) <----- should be something like that 

【问题讨论】:

  • 抱歉英语不好

标签: python django class model foreign-key-relationship


【解决方案1】:

您可以将其作为外键添加到用户模型中,

#if you are using  user model provided by django contrib 
from django.contrib.auth.models import User
class Note(models.Model): 
     #user other fields
     owner = models.ForeignKey(User)

【讨论】:

  • 我 syncdb 但没有安装对象。我运行服务器,我试图创建新的笔记,我得到了这个错误。数据库错误 。表 note_note 没有名为 owner_id 的列
  • 尝试为应用重置db,可能命令是python manage.py reset &lt;your_app_name&gt;,然后再次syncdb。
  • python manage.py sqlclear note
  • 由于某种原因,当我在 sqlclear 之后重新打开 slqlite 浏览器时,我仍然可以看到表格 note_note。所以它实际上并没有放弃它。
  • 我使用查询删除表(note_note)。并且工作了。我在创建新笔记时得到了这个 eo​​or(我已登录)。完整性错误:note_note.owner_id 可能不为 NULL
猜你喜欢
  • 1970-01-01
  • 2014-09-17
  • 2014-04-06
  • 1970-01-01
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-16
相关资源
最近更新 更多