Create a table with initial data in Django

Asked

Viewed 429 times

1

I want to create a table with the names/ types of a template, in this case, are documents, I have this template code

class Document(models.Model):
    hash = models.CharField(max_length=256)
    name = models.CharField(max_length=100)
    date_created = models.DateField(auto_now_add=True)
    process_owner = models.ForeignKey(Process, default=1, on_delete=models.SET_DEFAULT)

In this case, I want to exchange the name for a Foreign key of a table with all the names already instantiated. How do I create this table already populated with Django?

  • 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.

  • Yes, but I want this table to be populated with initial and fixed data, that’s the question

  • Which one: the names or the documents? and where would this data come from?

  • 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

  • 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.

  • 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

  • Okay, I’ll answer with an example

  • @Sidon Thanks

Show 3 more comments

1 answer

1


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

  • 1

    As I’m only making the prototype yet, I think with fixtures makes more sense, because it’s simpler, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.