How to load sql fixture in Django for User model?

2019-01-22 00:19发布

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

7条回答
不美不萌又怎样
2楼-- · 2019-01-22 00:56

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.

查看更多
登录 后发表回答