Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using django ORM from non django python script

Here is the scenario. I have Django project and python script project under a directory. The python script needs to runs independently on a scheduled time and also needs to access Database used by Django.

Is it possible to use/import existing Django code in python script to access db. If so how?

The idea comes for C# app where Models and data access layer can be built as library and can be used in many projects.

like image 978
Pavan Kumar Avatar asked Aug 30 '26 11:08

Pavan Kumar


1 Answers

Yes, you can use just the ORM part of Django, without using the web parts.

The directory for your Django application will need to be in your PYTHONPATH, you'll have to explicitly set os.environ["DJANGO_SETTINGS_MODULE"], and you'll have to import whatever models you want to use. From there, you can create and update models as usual:

from myapp.models import Customer, Order
c = Customer.objects.create(name='John Smith')
orders = Order.objects.filter(customer__name='Mary Brown')
like image 84
John Gordon Avatar answered Sep 02 '26 05:09

John Gordon