1👍
There are several ways to do it. To minimize learning curve, perhaps making use of crontab and creating a Django management command will be a good path to get started:
# <YOUR_APP>/management/commands/transfer.py
from django.core.management.base import BaseCommand
from django.db import transaction
from <YOUR_APP>.models import MyModel
class Command(BaseCommand):
help = "Transfer one thousand copies from Object B to A of MyModel"
def add_arguments(self, parser):
parser.add_argument("--quantity", type=int, default=1000)
def handle(self, *args, **options):
a = MyModel.objects.get(name="A")
b = MyModel.objects.get(name="B")
quantity = options["quantity"]
with transaction.atomic():
a.quantity += quantity
a.save()
b.quantity -= quantity
b.save()
Then you can run:
python manage.py transfer
to transfer your quantity.
You can also specify your quantity as well (by default it’s 1000 as you expect):
python manage.py transfer --quantity 2000
Next is automation. Run crontab -e
and append one line:
0 4 * * 0 /usr/bin/python <REPLACE_IT_WITH_YOUR_DJANGO_PROJECT_PATH>/manage.py transfer
0 4 * * 0
means crontab will try to execute this command at 04:00 every Sunday – you can check and tweak this expression on Crontab.guru.
Perhaps you are using a virutalenv instead of system-level Python interpreter to run your application code. If so, you should replace /usr/bin/python
with the result of which python
you run on your terminal.