Paul Bernhard Wagner Paul Bernhard Wagner - 5 months ago 29
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 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
. 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 ?


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 loaddata yourfilename the data gets loaded into the database.

In the example above the json file should look like:

    "model": "",
    "fields": {
        "name": "Hemingway"