1

I have a 2 models that I wish to interact/update every 7 days without needing me to execute. ( wether the website is online or offline )( local hosting for now )

class Model: name = model... quantity = models.IntegerField(default=0)

obj A name = A quantity = 0

obj B name = B quantity = 1,000,000

I'm trying to find a way to transfer 1000 from obj B to obj A, every 7 days.

I am looking but still can't find an answer that simplifies this situation.

Thanks for the help!

I haven't tried anything yet since I do not know where to start. I know how to update objects manually, on page load or with signals.

it may have something to do with DateTime but I am not sure. Currently, there is no date field in the model.

Or celery, but I have never used it before.

1 Answers1

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.

Aris Chow
  • 178
  • 2
  • 6