Forums

Scheduled task to update models.py record

Hi,<br> I need to run overnight daily tasks to update the Events in models.py, if, in the past, the Event status changed to "Completed" in the database.

I set up the tasks.py file with the functions to do this, and added file to Tasks in PA:

/home/myusername/project_name/my_app/tasks.py

Within tasks.py I have:

from .models import Events

Which gave me an error:

from .models import Events
ImportError: attempted relative import with no known parent package

Also changing to:

import my_app.models

or

from my_app.models import Events

gave me an example error:

from my_app.models import Events
ModuleNotFoundError: No module named 'my_app'

The models.py is in the same directory, with __init__.py file:

/home/myusername/project_name/my_app/models.py

Settings.py is under:

/home/myusername/project_name/my_app_2/settings.py

Manage.py is under:

/home/myusername/project_name/manage.py

What should the working directory, not have the import issue? What should I put on top of the tasks.py to import the modules.py ? os, path (absolute path)? Also, will that actually update the database? <br><br>(I don't get it, eg. views.py use import .models and no issue there, how come tasks.py have the issue if files are under the same directory? Why this is different - when adding tasks.py after the whole app went into production)

Relative imports can be complicated if you do not have a good understanding of Python's import mechanism. See this stackoverflow post for an explanation of how they work and what you can do in your script.