database - 在 Django 中,如何在我的 models.py 中包含一些默认记录?

标签 database django django-models

如果我有一个类似 models.py 的

class WidgetType(models.Model):
     name = models.CharField(max_length=200)

class Widget(models.Model):
     typeid = models.ForeignKey(WidgetType)
     data = models.CharField(max_length=200)

当我知道我只会有几种类型的小部件时,如何为 WidgetType 构建一组内置常量值?显然,我可以启动我的管理界面并手动添加它们,但我想通过将其内置到 python 中来简化配置。

最佳答案

你可以使用固定装置:

http://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-data-with-fixtures

严格来说,固定装置不是模型的一部分,也不是任何 Python 代码的一部分。如果你真的需要在你的 python 代码中使用它,你可以监听 post_migrate通过 ORM 发出信号并插入您的数据,例如:

from django.db.models.signals import post_migrate

def insert_initial_data(sender, app, created_models, verbosity, **kwargs):
    if WidgetType in created_models:
        for name in ('widgettype1', 'widgettype2', 'widgettype3'):
            WidgetType.objects.get_or_create(name=name)

post_migrate.connect(insert_initial_data)

关于database - 在 Django 中,如何在我的 models.py 中包含一些默认记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2753211/

相关文章:

mysql - 什么是 SELECT col1 FROM table WHERE col2=somestring 的 Django ORM 等价物?

php - 如何规范这个汽车零件数据库?

database - Schemaspy 与敏感数据一起使用是否安全?

python - 需要快速更新 Django 模型与其他两个模型之间的差异

django - 测试 Django View 时出现断言错误

Django makemigrations 未检测到项目/apps/myapp

php - 错误号 : 2006, MySQL 服务器已消失 codeigniter sql 查询

sql - 按公共(public)字段组合两个查询组的输出

python - 没有名为 _imagingft 的模块

django - 使用 Django 上传图像