Python Tech

近期遇到的Django问题整理

错误提示:

accounts.profile: Reverse query name for field ‘mentor’ clashes with related field ‘User.profile’. Add a related_name argument to the definition for ‘mentor’.
django.db.utils.IntegrityError: accounts_profile.hire_date may not be NULL
django.db.utils.IntegrityError:accounts_profile.mentor_id may not be NULL

出错代码:


#models.py
class Profile(models.Model):
    user = models.OneToOneField(User)
    hire_date = models.DateField()
    mentor = models.ForeignKey(User)
    pl = models.ForeignKey(User)

出错原因和解决方案:

以上3个错误都是在制作User.Profile时出现的。

第一个错误,是因为在同一个model中为两个字段指定同一个外键,解决方法在错误提示中已经告知了:添加related_name。

第二个错误,让hire_date字段可以为空即可。


#models.py
class Profile(models.Model):
    user = models.OneToOneField(User)
    hire_date = models.DateField( blank = True)
    mentor = models.ForeignKey(User, related_name='trainees')
    pl = models.ForeignKey(User, related_name='team_members')

第三个错误很有趣,它的提示和第二个错误一样,于是我就在mentor和pl字段上添加了null = True,但运行时它又报了第二个错误,最后将代码改成以下形式以后正常了:


#models.py
class Profile(models.Model):
    user = models.OneToOneField(User)
    hire_date = models.DateField( null = True)
    mentor = models.ForeignKey(User, null = True, related_name='trainees')
    pl = models.ForeignKey(User, null = True, related_name='team_members')

之前的blank = True突然失效了。具体是Django本身的问题还是其他问题还在研究中。


错误提示

Error: Can’t find the file ‘settings.py’ in the directory containing ‘manage.py’. It appears you’ve customized things.
You’ll have to run django-admin.py, passing it your settings module.
(If the file settings.py does indeed exist, it’s causing an ImportError somehow.)

出错原因和解决方案:

这个问题和代码无关。settings.py文件好好的放着,但就是提示找不到文件。我在Stackoverflow上看到有人回答,说是因为在App中添加了下面这句,引起 “circular dependency” 导致的,但去掉这句以后问题依旧。但同样的代码放到windows环境下却一点问题也没有。


from django.db import models
0 0 投票数
文章评分
订阅评论
提醒
guest

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

3 评论
最新
最旧 最多投票
内联反馈
查看所有评论
pureboy
pureboy
6 年 前

大佬那么最后一个在windows环境下也报错。

Luz
Luz
12 年 前

很不错的博客,长期关注!

minind
12 年 前

在详细点。。。内容不错