1👍
You need to initialise the project first. You don’t usually have to do this when going through manage.py, because it does it automatically, but a new process won’t have had this done for it. So you need to put something like the following at the top of your code:
import django
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
django.setup()
myproject.settings
needs to be importable from whereever this code is running, so if not you might need to add to sys.path
first.
Once this is done you can access your project’s models, and use them to access your database, just like you normally would.
1👍
I was having a similar problem (also starting process from view), and what eventually helped me solve it was this answer.
The solution indicated is to close your DB connections just before you fork your new Process, so Django can recreate the connection when a query is needed in the new process. Adapted to you code it would be:
def post(self, request):
v = Value('b', True)
#close db connections here
from django import db
db.connections.close_all()
#create and fork your process
proc = Process(target=start, args=(v, request.user,
request.data['stock'], request.data['pair'], '1111'))
proc.start()
Calling django.setup()
did not help in my case, and after reading the linked answer, probably because forked processes already share the file descriptors, etc. of its parent process (so Django is already setup).
- [Django]-Django logging: Cannot create logs per day
- [Django]-Django raw sql format tablename
- [Django]-Django ModelChoiceField allow objects creation
- [Django]-Django order queryset by OnetoOneField