我正在尝试使用SQLite3
Django
和ORM
函数来更新update()
数据库中的记录。
我可以看到,在独立脚本中运行update()
函数之后,数据库实际上已经更新,但是直到我重新启动gunicorn
时,更改才会反映在我的网站上: / p>
sudo systemctl restart gunicorn
我怀疑问题与将模型导入独立脚本的方式有关。
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)
这部分代码每天在我的服务器上运行一次。 我希望无需重新启动gunicorn就可以在我的网站上看到更新。
更多上下文:我正在同一独立脚本中运行create()
函数,该脚本正在更新数据库并按预期反映在我的站点上,而不必重新启动gunicorn
。
答案 0 :(得分:2)
也许这不是您问题的直接答案,但是对于Django中的独立脚本,我建议使用custom management commands。这样可以避免设置和环境变量。
例如,您可以编写脚本main/management/commands/my_script_1.py
(阅读有关其运行原因的文档):
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)]))
然后您可以像在Linux中这样调用脚本:
$ ./manage.py my_script_1
或者,如果您的代码位于虚拟环境中,但想通过cron
作业来调用脚本,则:
$ 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