2

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 ?

Tom
  • 2,545
  • 5
  • 31
  • 71
  • 5
    You should not try to do this via the ORM, but [like so](https://docs.djangoproject.com/en/1.8/howto/initial-data/). There may or may not be automatic loading available depending on your version of Django, but note they list this behavior as deprecated. – Two-Bit Alchemist Sep 08 '15 at 21:51
  • 1
    ahh initial data, that's the term is was looking for, thanks! – Tom Sep 08 '15 at 21:52
  • tell me if this helps: http://stackoverflow.com/questions/6791911/execute-code-when-django-starts-once-only – Alvaro Silvino Sep 08 '15 at 22:04

1 Answers1

0

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"
    }
  }
]
Tom
  • 2,545
  • 5
  • 31
  • 71