Reputation: 1881
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
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
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