Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load sql fixture in Django for User model?

Does anyone knows how to load initial data for auth.User using sql fixtures? For my models, I just got have a < modelname >.sql file in a folder named sql that syncdb does it's job beautifully. But I have no clue how to do it for the auth.User model. I've googled it, but with no success.

Thanks in advance,

Aldo

like image 787
aldux Avatar asked Mar 09 '10 20:03

aldux


People also ask

How do I load all fixtures in Django?

By default, Django only loads fixtures into the default database. Use before_scenario to load the fixtures in all of the databases you have configured if your tests rely on the fixtures being loaded in all of them. You can read more about it in the Multiple database docs.

How do I use fixtures in Django?

By default, Django looks in the fixtures directory inside each app for fixtures. You can set the FIXTURE_DIRS setting to a list of additional directories where Django should look. When running manage.py loaddata , you can also specify a path to a fixture file, which overrides searching the usual directories.

Can we use SQL with Django?

Django officially supports five database management systems: PostgreSQL, MariaDB, MySQL, Oracle, and SQLite (Django, 2020). Some third parties provide backends for other DBMSs, such as CockroachDB, Firebird, and Microsoft SQL Server.

What is populate in Django?

Project description *django-populate* provides an adapter for Django Models, for easy population of test databases. To populate with Model instances, create a new Populator class, then list the class and number of all of Models that must be generated. To launch the actual data population, call `execute()` method.


2 Answers

For SQL fixtures, you'd have to specifically have insert statements for the auth tables. You can find the schema of the auth tables with the command python manage.py sql auth.

The much easier and database-independent way (unless you have some additional SQL magic you want to run), is to just make a JSON or YAML fixture file in the fixtures directory of your app with data like this:

- model: auth.user
  pk: 100000
  fields:
    first_name: Admin
    last_name: User
    username: admin
    password: "<a hashed password>"

You can generate a hashed password quickly in a django shell

>>> from django.contrib.auth.models import User
>>> u = User()
>>> u.set_password('newpass')
>>> u.password
'sha1$e2fd5$96edae9adc8870fd87a65c051e7fdace6226b5a8'

This will get loaded whenever you run syncdb.

like image 186
Derek Dahmer Avatar answered Sep 29 '22 19:09

Derek Dahmer


You are looking for loaddata:

manage.py loadata path/to/your/fixtureFile

But I think the command can only deal with files in XML, YAML, Python or JSON format (see here). To create such appropriate files, have a look at the dumpdata method.

like image 39
Felix Kling Avatar answered Sep 29 '22 18:09

Felix Kling