djangodjango-modelscrondjango-crondjango-crontab

Django-crontab can't make model query


I have a model inside tools app called ApiKeys and tried to update the model in specific time intervels. I used django-crontab for this purpose.

CRONJOBS = [
    ('*/1 * * * *', 'tools.cron.reset_api_calls','>>logs.log')
]

function -

from .models import ApiKeys

def reset_api_calls():
    try:
        keys = ApiKeys.objects.all()
            for key in keys:
                key.api_calls = 0
                key.save()
    except Exception as e:
        print(e)

model -

class ApiKeys(models.Model):
    key_token = models.CharField(max_length=50, primary_key=True)
    api_calls = models.IntegerField(default=0)
    las_used_date = models.DateTimeField(default=timezone.now)

But it gives error log - no such table: tools_apikeys

Note: The table does exist in database and accessible through django-shell and views.py as well.


Solution

  • It doesn't work that way, as you need to setup Django for these command to work

    You have 2 options

    1. Implement this as a management command

    2. Setup Django manually as the start of your script.

       import django
       os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
       django.setup()