Django database models outside of the script

Django database models outside of the script

If you are not running at the time of Django's call the ORM models from external databases directly lead pack is not acceptable. Because of the need to run model Django environment. At this point, we need to configure Django environment into the system.

Code configuration can be found in the manage.py file.

Sample code:

import os

if __name__ == '__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "orm02.settings")
    import django
    django.setup()
    
    from app01 import models
    ret = models.Book.objects.all().values('title')
    print(ret)

Guess you like

Origin www.cnblogs.com/shuoliuchina/p/12521600.html