【问题标题】:providing initial data to django model为 django 模型提供初始数据
【发布时间】:2013-09-11 17:08:26
【问题描述】:

如何使用初始数据填充表。 ?? 我读过这个: [1]https://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data

目录树:

|-- 管理.py |-- 数据库 |-- 质量保证 | |-- __init__.py | |-- __init__.pyc | |-- 迁移 | | |-- 0001_initial.py | | |-- 0001_initial.pyc | | |-- 0002_auto__add_report__add_questioncontainer.py | | |-- 0002_auto__add_report__add_questioncontainer.pyc | | |-- __init__.py | | `-- __init__.pyc | |-- 模型.py | |-- 模型.pyc | |-- sql | | |-- 问题容器.sql | | `-- 废品.py | |-- 测试.py | `--views.py `--QA网站 |-- __init__.py |-- __init__.pyc |-- 设置.py |-- 设置.pyc |-- urls.py `--wsgi.py

模型文件:

from django.db import models
class QuestionContainer(models.Model):
    topic           = models.CharField(max_length=100)
    subtopic        = models.CharField(max_length=100)
    question        = models.TextField()
    options         = models.TextField()
    correct_answer  = models.CharField(max_length=50)
    total_attempts  = models.IntegerField()
    solved          = models.IntegerField()
    level           = models.IntegerField()

class Report(models.Model):
    name                = models.CharField(max_length=200)
    email               = models.EmailField()
    content             = models.TextField()
    QuestionContainer   = models.ForeignKey(QuestionContainer)

questioncontainer.sql 包含

INSERT INTO QAapp_QuestionContainer (topic,subtopic,question,options,correct_answer,total_attempts,solved,level) VALUES ('general-aptitude','age-problems','The Average age of a class of 22 students in 21 years. The average increases by 1 when the teachers age also included. What is the age of the teacher?','A. 44 C. 41 B. 43 D. 40','[A]',0,0,0);

问题是:我是否需要添加一些东西来 manage.py [或] 从 shell [或] 任何其他东西执行一些命令以便用这些插入查询填充表??

我试过了:
python manage.py sqlall
python manage.py syncdb

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    是的,你需要运行:

    python manage.py syncdb
    

    这将创建所有表,然后运行您的 sql 脚本..

    更新:

    由于您使用的是 south,因此控制 syncdb 并提供 migrate 的 south 似乎会在创建表后模仿 syncdb 并加载 sql 文件。我在 DjangoSnippets 上找到了这个 sn-p,它可以让你对南做同样的事情。考虑页面右侧的注释,您可能需要更改 sql 文件名。 此代码发布于 2011 年,我不确定南方是否仍然如此。

    http://djangosnippets.org/snippets/2311/

    【讨论】:

    • 把那个函数放在哪里??在models.py ??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 2015-06-14
    • 2021-05-21
    • 2013-05-05
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多