Pavan Kumar
Pavan Kumar

Reputation: 1881

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.

Upvotes: 2

Views: 1869

Answers (2)

dyezepchik
dyezepchik

Reputation: 1

Faced the same problem and finally decided to implement a daemon in django custom command. You can import anything django related there just as you would normally do in django code, while implementing your own code.

Upvotes: 0

John Gordon
John Gordon

Reputation: 33335

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')

Upvotes: 5

Related Questions