You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Django执行migrate时自动生成数据库预设对象?

解决方法:用Django数据迁移自动生成预设对象

要在执行python manage.py migrate时自动往数据库插入预设数据,直接用Django的**数据迁移(Data Migrations)**就能实现,不用手动进后台配置。下面是针对你给出的模型的具体操作步骤:

1. 生成空的迁移文件

针对每个需要添加预设数据的应用,运行以下命令生成空迁移文件:

# 替换成你的实际应用名,比如第一个模型所在app叫api,第二个叫site_messages
python manage.py makemigrations --empty api
python manage.py makemigrations --empty site_messages

2. 编辑迁移文件,添加数据创建逻辑

打开生成的迁移文件(比如api/migrations/0002_auto_xxxxxx_xxxx.py),修改成对应模型的逻辑:

针对apikey模型的迁移示例

from django.db import migrations
from api.models import apikey

def create_default_apikey(apps, schema_editor):
    # 创建默认的apikey记录
    apikey.objects.get_or_create(key="default_key")

class Migration(migrations.Migration):

    dependencies = [
        ('api', '0001_initial'),  # 这里要和你的初始迁移文件名一致
    ]

    operations = [
        migrations.RunPython(create_default_apikey),
    ]

针对message模型的迁移示例

打开另一个应用的空迁移文件,添加创建默认message记录的逻辑:

from django.db import migrations
from site_messages.models import message

def create_default_message(apps, schema_editor):
    # 创建唯一的message记录(适配你的单条数据场景)
    message.objects.get_or_create(
        visitmessage="# 欢迎访问",
        ourvision="# 我们的愿景"
    )

class Migration(migrations.Migration):

    dependencies = [
        ('site_messages', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_default_message),
    ]

针对video模型(可选)

如果需要预设video数据,在对应迁移文件中添加:

from django.db import migrations
from datetime import date
from api.models import video

def create_default_video(apps, schema_editor):
    video.objects.get_or_create(
        official_name="默认视频",
        date=date.today(),
        vid="default_vid",
        thumbnail_url="https://example.com/default.jpg",
        biblestudy=False
    )

class Migration(migrations.Migration):

    dependencies = [
        ('api', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_default_video),
    ]

3. 执行迁移

运行python manage.py migrate,Django会自动执行这些迁移逻辑,把预设数据插入数据库。

为什么用get_or_create?

用get_or_create而非直接create,是为了避免重复执行迁移时创建多条相同数据——如果记录已存在,就不会生成新条目。

内容的提问来源于stack exchange,提问作者callen44

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:05:09