扩展关系字段参数列表

时间:2017-08-29 13:58:13

标签: django django-models django-migrations

我正在寻找扩展关系字段参数列表的方法,例如为关系的每个方向添加谓词。我的第一个猜测是定义models.ForeignKey

的子类
class NewForeignKey(models.ForeignKey):

    def __init__(self, parent, pred='', reverse_pred='', **kwargs):
        self.pred = pred,
        self.reverse_pred = reverse_pred
        super(NewForeignKey, self).__init__(parent, **kwargs)

然后在我的模型中使用此子类,如下例所示:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = NewForeignKey (Question,
                              pred="refers to",
                              reverse_pred="includes",
                              on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

最初,这似乎工作正常,但是,当我尝试通过makemigrations时,它失败并显示以下错误消息:

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 346, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 394, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 445, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\commands\makemigrations.py", line 99, in handle
    ProjectState.from_apps(apps),
  File "C:\Python27\lib\site-packages\django\db\migrations\state.py", line 178, in from_apps
    model_state = ModelState.from_model(model)
  File "C:\Python27\lib\site-packages\django\db\migrations\state.py", line 354, in from_model
    e, 
TypeError: Couldn't reconstruct field question on polls.Choice: __init__() takes at least 2 arguments (1 given)

为了使事情变得更简单,我尝试从头开始迁移,如下所示:

  1. 首先没有FK,
  2. 然后将FK添加为models.ForeignKey
  3. 最后用models.ForeignKey
  4. 替换了NewForeignKey

    步骤(1)和(2)之后的迁移成功(显然)。 {(1}}在步骤(3)之后始终以相同的结果失败,无论我是否跳过步骤(2)。

    深入挖掘,我找不到解释为什么这不可能。我知道Django模型必须从makemigrationssee here)创建子类,但django.db.models.Model不是这种情况。

    对此问题的澄清和/或对允许使用其他关系字段参数的变通方法或巧妙替代方案的任何建议将不胜感激。

0 个答案:

没有答案