我如何向Django模型提供初始数据?

ddrv8njm  于 2023-01-03  发布在  Go
关注(0)|答案(1)|浏览(110)

我已经阅读了Django关于提供初始SQL数据的文档
定向树:

|-- manage.py
    |-- mydb
    |-- QAapp
    |   |-- __init__.py
    |   |-- __init__.pyc
    |   |-- migrations
    |   |   |-- 0001_initial.py
    |   |   |-- 0001_initial.pyc
    |   |   |-- 0002_auto__add_report__add_questioncontainer.py
    |   |   |-- 0002_auto__add_report__add_questioncontainer.pyc
    |   |   |-- __init__.py
    |   |   `-- __init__.pyc
    |   |-- models.py
    |   |-- models.pyc
    |   |-- sql
    |   |   |-- questioncontainer.sql
    |   |   `-- scrap.py
    |   |-- tests.py
    |   `-- views.py
    `-- QAsite
        |-- __init__.py
        |-- __init__.pyc
        |-- settings.py
        |-- settings.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

x33g5p2x

x33g5p2x1#

是的,您需要运行:

python manage.py syncdb

这将创建所有表,然后运行sql脚本。

    • 更新日期:**

既然你用南方,看起来south控制了syncdb并提供了migrate,而不是模仿syncdb并在创建表后加载sql文件。我在DjangoSnippets上找到了这个片段,它可以让你对south做同样的事情。考虑页面右侧的注解,你可能需要更改sql文件名。这个代码张贴在2011年,我不确定这是否仍然是南方的情况。
http://djangosnippets.org/snippets/2311/

相关问题