pythondjangocronscheduled-tasksdjango-shell

Execute Django shell command as cron


I'm try to Execute Django shell command as cron, I have some queries and objects tasks to search and read and write using the models and queries of my django app.

How can I execute this 1 or 2 times a day?

For example, how can I run these queries periodically:

from django.contrib.auth.models import User
from perfil.models import *

for user in usuarios:
        profiles = Perfil.objects.filter(user=user)
        create_task = Task.objects.create(user=user)

Solution

  • Take a look at Custom management commands for django.

    As a basic example:

    from django.core.management.base import BaseCommand, CommandError
    from django.contrib.auth.models import User
    from perfil.models import *
    
    class Command(BaseCommand):
    
        help = 'What does this do? '
    
        def handle(self, *args, **options):
            for user in usuarios:
                profiles = Perfil.objects.filter(user=user)
                create_task = Task.objects.create(user=user)
    

    On a side note, you should be more explicit about your import and not use from perfil.models import *.

    From that, you can execute the command based on the file you saved it in. If you saved the file in yourapp/management/commands/dofunstuff.py than you could execute it via python manage.py dofunstuff.