如何保留在就绪方法中创建的数据? Django 生产与测试数据库

时间:2021-06-28 11:58:11

标签: django

如您所知,django 在测试中为您提供了清晰的数据库,但我有一个 ready() 方法可以为我创建一些数据,我需要在测试中查询这些数据。


class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.AutoField'
    name = 'Functions.MyAppsConfig'
    def ready(self):
        from django.contrib.auth.models import Permission
        from django import apps
        from django.contrib.contenttypes.models import ContentType

       try:
          Permission.objects.get_or_create(....)
          MyOtherModel.objects.get_or_create(....)
      except:
          pass

class TestRules(APITestCase):

    def test_my_model(self):
        ....
        x = MyOtherModel.objects.filter(....).first()
        # x = None # <=========== problem is here ========= I need to see the data that I created in the ready method
        ....
        

1 个答案:

答案 0 :(得分:0)

您可以为此使用固定装置,在每个测试用例中您都可以固定它,如所述 documentation 示例是

class Test(TransactionTestCase):
    fixtures = ['user-data.json']
    def setUp():
       …

Django 将在测试用例之前加载夹具