Reputation: 71
I have created my database models in my model.py file, but I want to be able to populate them with data. I have the code written that reads in the data from a text file I have and create the objects for my models. But I am not sure where to actually run this code, all the tutorials I can find they only create the objects through the shell, but since I am reading in from a text file and since the code is quite long I dont want to use the shell. My solution was to create a file called buildDB in my application folder, and run the code there, but this will not work:
if I try to import my models at top of file using
from .models import *
I get
ImportError: attempted relative import with no known parent package
when I run it.
If I try using from applicatonName.models import*
I get
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
When I google the second error message, it would appear that this happens becasue I am not using manage.py shell, and the first error message I dont even know. Do I have to use shell to populate data base? Where would I put my code if not?
Upvotes: 1
Views: 419
Reputation: 5549
a) It looks like you should write a data migration: https://docs.djangoproject.com/en/3.0/topics/migrations/#data-migrations
b) Another option would be to write a "custom command": https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/
c) And finally, you could write an external script that initializes django and creates all model objects from the file: simply a python script in the same folder as the django project (or in a scripts
folder) that runs django.setup()
at the beginning. This script can import and use the models and the ORM and create all database objects.
You have attempted (c) without success, because you were missing the django.setup()
part.
If this is some data that should be populated initially in every instance of the application (for instance, testing, pre-production and production), then I would pick a)
If you will have to load similar files from time to time, and the file is different each time, maybe b) or c). The later two options are quite similar, and probably a custom command is something cleaner (although you need to read the docs about writing custom commands)
Upvotes: 2