如何为Django模型定义默认数据? [英] How to define default data for Django Models?

查看:64
本文介绍了如何为Django模型定义默认数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的应用程序具有默认数据,例如用户类型.

迁移后管理默认数据的最有效方法是什么?

它需要处理诸如添加新表后为其添加默认数据之类的情况.

解决方案

更新:

大多数用户都在按照@durdenk在 https://stackoverflow.com/a/39742847/3627387 .但是OP询问的是关于迁移后添加数据的方法,这就是为什么这是可以接受的答案.

原始答案:

我认为您正在寻找的是夹具 https://docs.djangoproject.com/en/1.10/howto/initial-data/

来自文档

在初次设置应用程序时,有时用硬编码数据预填充数据库有时会很有用.您可以通过灯具提供初始数据.

也请阅读此 https://code.djangoproject.com/wiki/Fixtures

I want my application to have default data such as user types.

What's the most efficient way to manage default data after migrations?

It needs to handle situations such as, after I add a new table, it adds the default data for it.

解决方案

Update:

most users are looking for data migration as suggested by @durdenk in https://stackoverflow.com/a/39742847/3627387. But what OP was asking is about a way to add data after migrations, that is why this is accepted answer.

Original answer:

I think what you are looking for is fixtures https://docs.djangoproject.com/en/1.10/howto/initial-data/

From docs

It’s sometimes useful to pre-populate your database with hard-coded data when you’re first setting up an app. You can provide initial data via fixtures.

Also read this https://code.djangoproject.com/wiki/Fixtures

这篇关于如何为Django模型定义默认数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆