create model instance

14 views
Skip to first unread message

djangoer

unread,
Jun 4, 2008, 2:31:55 PM6/4/08
to Django users
A quick newbie question,

is there any way that can create a default instance (a pre-specified
instance) in the database once the model is created. In other words,
when we first run the syncdb(or set up the website), an pre-defined
instance is created.

For example, we have a Book model,

class Book(models.Model):
author = models.CharField(maxlength = 50)
title = models.CharField(maxlength = 50)

When the website is first setup, we would like to have one default
"Book" instance in the DB, say Book("John.Smith","COMPUT101").

Your help is greatly appreciated.

Chris Czub

unread,
Jun 4, 2008, 2:35:38 PM6/4/08
to django...@googlegroups.com
http://www.djangoproject.com/documentation/models/fixtures/

What you are looking for is an initial_data fixture. You need to serialize the default instance of the model you want as JSON and save it in initial_data.json and then it should prepopulate when you run syncdb.

djangoer

unread,
Jun 4, 2008, 11:53:17 PM6/4/08
to Django users
thanks very much Chris.

I googled and also find some related articles.

http://www.djangoproject.com/documentation/0.96/models/fixtures/
http://code.djangoproject.com/wiki/Fixtures

However, when I tried to reset and syncdb, I always had error
messages.

1.$ python manage.py reset myapp
Type 'yes' to continue, or 'no' to cancel: yes
Error: myapp couldn't be reset. Possible reasons:
* The database isn't running or isn't configured correctly.
* At least one of the database tables doesn't exist.
* The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlreset myapp'. That's
the SQL this command wasn't able to run.
The full error: ERROR: constraint
"reference_id_id_refs_id_4d6e9d1fab032af2" does not exist

2.$ python manage.py syncdb
Loading 'initial_data' fixtures...
Installing json fixture 'initial_data' from '/home/myproject/myapp/../
myapp/fixtures'.
Problem installing fixture '/home/myproject/myapp/../myapp/fixtures/
initial_data.json': ['This value must be either True or False.']

Please advise. Thanks much!



"Chris Czub" <chris.c...@gmail.com> wrote:
> http://www.djangoproject.com/documentation/models/fixtures/
>
> What you are looking for is an initial_data fixture. You need to serialize
> the default instance of the model you want as JSON and save it in
> initial_data.json and then it should prepopulate when you run syncdb.
>
Reply all
Reply to author
Forward
0 new messages