1

我已经关注了 django 自定义命令教程,链接在这里

我的工作目录如下所示:

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 的第一个参数是我的模型 Units,如何让编译器的抱怨静音?

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服务器可以正常运行而命令行不能运行...

4

1 回答 1

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"
于 2013-03-29T03:12:31.280 回答