问题
I am trying to update records in my SQLite3
DB using the Django
ORM
and the update()
function.
I can see that after running the update()
function in my standalone script, the database has in-fact been updated, but the changes are not reflected on my website until I restart gunicorn
with:
sudo systemctl restart gunicorn
I suspect the issue has to do with the way I import my models into my standalone script.
ROOT_DIR = /path/to/root/dir
sys.path.insert(0, ROOT_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AppName .settings')
import django
django.setup()
from main.models import Bet, Investment, Profile
from django.contrib.auth.models import User
Bet.objects.filter(id=4).update(revenue=10)
This bit of code is being run once a day on my server. I would expect to see the updates reflected on my site without having to restart gunicorn.
More context: I am running a create()
function in the same standalone script which is updating the database and being reflected on my site as expected without having to restart gunicorn
.
回答1:
Maybe this is not a direct answer to your problem, but for a standalone script in Django, I suggest using custom management commands. This way you avoid the setup and environment variables.
For example, you could write a script main/management/commands/my_script_1.py
(read the docs about why it goes there):
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from main.models import Bet, Investment, Profile
class Command(BaseCommand):
def handle(self, *args, **options):
self.stdout.write('Before: {}'.format(
[(e.pk, e.revenue) for e in Bet.objects.filter(id=4)]))
# do the update of rows
Bet.objects.filter(id=4).update(revenue=10)
self.stdout.write('After: {}'.format(
[(e.pk, e.revenue) for e in Bet.objects.filter(id=4)]))
And then you can invoke the script like this (in linux):
$ ./manage.py my_script_1
Or, if you have your code inside an virtual env, but want to call your script form a cron
job:
$ crontab -l
0 5 * * * cd /path/to/project && /path/to/project/.venv/bin/python /path/to/project/manage.py my_script_1 > /dev/null 2>&1
来源:https://stackoverflow.com/questions/54158666/using-django-models-in-standalone-script-website-not-updating