Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在django中测试时的模型创建顺序?_Python_Django_Python 3.x_Testing - Fatal编程技术网

Python 在django中测试时的模型创建顺序?

Python 在django中测试时的模型创建顺序?,python,django,python-3.x,testing,Python,Django,Python 3.x,Testing,我有这两个模型(示例),当我试图运行我的测试时,它错误地说:没有这样的表:my_app_modelA——如果我向上滚动,我可以看到它在创建modelB时爆炸了(我假设这是由于应用了默认值)。是否有一种方法可以对这些模型进行排序,以便总是在模型B之前创建模型a?或者我不应该将该方法作为默认属性引用?只是想让我的测试正常进行,这是我的症结所在 我的模型是这样的: class modelA(models.Model): attribute = models.IntegerField()

我有这两个模型(示例),当我试图运行我的测试时,它错误地说:
没有这样的表:my_app_modelA
——如果我向上滚动,我可以看到它在创建
modelB
时爆炸了(我假设这是由于应用了
默认值
)。是否有一种方法可以对这些模型进行排序,以便总是在
模型B
之前创建
模型a
?或者我不应该将该方法作为默认属性引用?只是想让我的测试正常进行,这是我的症结所在

我的模型是这样的:

class modelA(models.Model):
    attribute = models.IntegerField()
    active = models.BooleanField(default=False)

    @classmethod
    def get_active_attribute(cls):
        return modelA.objects.get(active=True).attribute

class modelB(models.Model):
    attribute = models.IntegerField(default=modelA.get_active_attribute())
我的问题是:

  • 这是一件可以接受的事情吗?让默认调用另一个模型方法

  • 有没有一种方法可以处理这些模型的创建,我可以保证
    modelA
    首先创建,这样
    modelB
    就可以在我的测试中成功创建


首先,迁移按照创建迁移文件时定义的顺序进行

# 0001_initial.py
...
operations = [
    migrations.CreateModel(
        name=modelA,
        ....
    ),
    migrations.CreateModel(
        name=modelB,
        ....
    ),
]
您可以检查迁移文件,并确保
modelA
modelB
之前

其次,
modelA.get\u active\u attribute()
需要一个DB条目才能返回某些内容。运行迁移时,您没有插入数据。因此,您不应该通过其他模型的对象声明
default
。 您应该替代
save()
,以确保默认值基于
modelA
的属性

class modelB(models.Model):
    attribute = models.IntegerField()

    def save(self, *args, **kwargs):
        if self.attribute is None:
            self.attribute = modelA.get_active_attribute()
        super(modelB, self).save(*args, **kwargs)

我相信这是正确的答案。迁移是以这样的方式创建的:
modelA
迁移是在
modelB
之后创建的,但在初始迁移中,它使用了一个静态的
整数
。直到很久以后的一次更改,以前的开发人员才将其更改为使用该方法。现在,在看到你的答案后,这在实践中似乎是个坏主意。在生产环境中,总会有一个DB条目用于返回某些东西——显然,在测试中除外,这正是我所处的位置。试图在测试中解决这个问题。谢谢你的意见!