我跟着django自定義命令教程,鏈接是here。django自定義命令抱怨AssertionError:ForeignKey(None)無效。爲什麼
我的工作目錄是這樣的:
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的第一個參數是我的模型單位,我該如何沉默編譯器的comp laint?
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:我的網絡服務器可以運行沒有任何問題,而命令行無法運行...
你的錯誤是從models.py到來,似乎沒有有什麼用您的自定義命令。你能分享你的模特嗎? –
我相信對於你的外鍵你需要指定null = True屬性。 –
感謝Sidharth沙,我加入空=模型的確,抱怨不會消失...... – leffe