Paul Bernhard Wagner Paul Bernhard Wagner - 4 months ago 18
Python Question

how to create an entry in the database on start django

I have an app with

class Author(models.Model):
name = models.CharField(max_length=200)


and I want that when it is being started with
python manage.py runserver
that the it checks if the name 'Hemingway' is already created and if not it should be created. What's the best way of doing that?
I know how to do it manually over the shell or how to create it in with forms
Author.object.create(name='Hemingway')
. So, for example if I flush the database and restart my app, the name Hemingway will be created.

And in which file would that be done ?

Answer

Thanks to Two-Bit Alchemist one way is through Providing initial data with fixtures.

This means creating a fixtures folder with a yourfilename.json file. Then with python manage.py loaddata yourfilename the data gets loaded into the database.

In the example above the json file should look like:

[
  {
    "model": "visitors.author",
    "fields": {
        "name": "Hemingway"
    }
  }
]