我已经按照django自定义命令教程,链接是here。
我的工作目录如下所示:
myapps/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
my_command.py
tests.py
views.py
我的代码如下所示:
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
def handle(self, *args, **options):
print '=========='
self.stdout.write('Successfully closed poll ttt')
当我运行命令manage.py my_command时,我收到以下错误,
File "D:/ERP\apps\person\salary\models.py", line 8, in <module>
class Salarys(models.Model):
File "D:/ERP\apps\person\salary\models.py", line 14, in Salarys
Unit = models.ForeignKey(Units, verbose_name = u'def_unit, on_delete = models.PROTECT)
File "D:\Python27\Lib\site-packages\django\db\models\fields\related.py", line 910, in __init__
assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
AssertionError: ForeignKey(None) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'
显然,ForeignKey的第一个参数是我的模型单位,如何使编译器的投诉无声?
ps:我的模型看起来像这样: 我的模型现在看起来像这样。
class Salarys(models.Model):
'''
describe : salary table
author : liyang 2013-1-23
'''
User = models.ForeignKey(Users, verbose_name = u'account', on_delete = models.PROTECT)
Unit = models.ForeignKey(Units, verbose_name = u'def_unit', on_delete = models.PROTECT, null=True)
yy = models.IntegerField(u'year)
mm = models.IntegerField(u'month')
class Meta:
db_table = 'users_salarys'
class Units(models.Model):
'''
describe : def unit model
author : liyang 2012-12-4 11:45
'''
name = models.CharField(u'name',max_length = 20)
cname = models.CharField(u'company name',max_length = 20, blank = True, null = True)
aname = models.CharField(u'company short cut',max_length = 20, blank = True, null = True)
telephone = models.CharField(u'contact',max_length = 20, blank = True, null = True)
website = models.CharField(u'website',max_length = 25, blank = True, null = True)
address = models.CharField(u'address',max_length = 50, blank = True, null = True)
class Meta:
db_table = 'units'
...
奇怪的事情是
1:用户外键在单位执行时不会出现任何问题......
2:无法运行命令行时,我的Web服务器可以正常运行...
答案 0 :(得分:2)
您的课程Units
应该在课程Salarys
之前:
class Units(models.Model):
...
class Salarys(models.Model):
user = models.ForeignKey(Users, verbose_name = u'account', on_delete = models.PROTECT)
unit = models.ForeignKey(Units, verbose_name = u'def_unit', on_delete = models.PROTECT, null=True)
还有一个建议:以单数形式命名模型是最佳做法。 Django会自动“复数”它们。如果Django无法正确复数类名,您可以通过将以下内容添加到模型Meta来指定自己的复数:
class Meta:
verbose_name_plural = "salaries"