Django: How to create a model dynamically just for testing

后端 未结 11 844
鱼传尺愫
鱼传尺愫 2020-12-02 05:15

I have a Django app that requires a settings attribute in the form of:

RELATED_MODELS = (\'appname1.modelname1.attribute1\',
                  \         


        
11条回答
  •  忘掉有多难
    2020-12-02 05:46

    If you are writing a reusable django-app, create a minimal test-dedicated app for it!

    $ django-admin.py startproject test_myapp_project
    $ django-admin.py startapp test_myapp
    

    add both myapp and test_myapp to the INSTALLED_APPS, create your models there and it's good to go!

    I have gone through all these answers as well as django ticket 7835, and I finally went for a totally different approach. I wanted my app (somehow extending queryset.values() ) to be able to be tested in isolation; also, my package does include some models and I wanted a clean distinction between test models and package ones.

    That's when I realized it was easier to add a very small django project in the package! This also allows a much cleaner separation of code IMHO:

    In there you can cleanly and without any hack define your models, and you know they will be created when you run your tests from in there!

    If you are not writing an independent, reusable app you can still go this way: create a test_myapp app, and add it to your INSTALLED_APPS only in a separate settings_test_myapp.py!

提交回复
热议问题