You can create the table normally and then create a command to populate it at the time you want, as you said (in the comments) that the data will be "hardcoded", I’ll give a good example "simplão" and "basicão", so you just adapt.
Let’s say your Django app is called core
, create a module called management
and, inside it another one called Commands and then a file called initialdata.py
, the structure should look something like this:
core
├── __init__.py
├── management
│ ├── commands
│ │ ├── initialdata.py
│ │ ├── __init__.py
Create the command inside initialdata.py
:
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.db.models import Q
class Command(BaseCommand):
help = 'Create initial data'
def handle(self, *args, **options):
if User.objects.filter(Q(username='admin') & Q(is_superuser=1)):
# Primeiro limpe a tabela
Document.objects.all().delete()
# Agora popule-a
# Repita a linha abaixo para qtos registros vc precisar.
Document.objects.create(field1 = value1,.... fieldN = valueN)
else:
print('Inclua um usuário superuser com o nome admin')
Okay, now to put this data in the table, do it on your command line:
python manage.py initialdata
Note that, the way I did, to use the command you need, before, to create a superuser with the name admin.
Using fixtures
The common practice in the Django community, for initial data is through fixtures, for this just create a directory called fixtures
within your app and then create a json, so the command Manage.py loaddata fixturename, populates a(s) table(s), automatically, but using a command becomes more flexible because you can read other tables (as is your case) and/or do other process before writing to the target table, if you want to experiment with fixtures, see that link
Final consideration:
Hardcoded is heim hardness? I suggest creating a json and making a function for Lenin, within initialdata.py
Don’t get it, you want the name to be a FK of a table that contains the names? if that’s just do the same way you did with
process_owner
.– Sidon
Yes, but I want this table to be populated with initial and fixed data, that’s the question
– Vinicius Macelai
Which one: the names or the documents? and where would this data come from?
– Sidon
I want to create a table with initial and fixed data, it will contain the id and a string of the name, and I want to change the name field to a Foreign key of this table, the question is how to create the table already with data, these data will be hardcoded
– Vinicius Macelai
There is no need to "create the table already with the data", create the table normally and then create a command to populate it, simple.
– Sidon
But that’s the question, how do you do that? I don’t want to have to open the postgres or the admin Django and put in hand all the data every time I install the app, there must be a smarter way
– Vinicius Macelai
Okay, I’ll answer with an example
– Sidon
@Sidon Thanks
– Vinicius Macelai