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

时间:2013-05-18 08:58:40

标签: python django

如何向包含foreignkeys和datetimefield的django模型提供初始数据。

例如::

仲裁/ models.py

class Question(models.Model):
    user=models.ForeignKey(User)
    created=models.DateTimeField(auto_now_add=True)
    question=models.TextField()
    tags=models.CharField(max_length=50)

仲裁/装置/ questions.json

[
    {
    "model": "quorum.question",
    "pk": 1,
    "fields": {
        "question": "what is cryptography in computer science?",
        "tags": "computer science, cryptography."
    }
    },
    {
    "model": "quorum.question",
    "pk": 2,
    "fields": {
        "question": "How python language got name? from snake? is it from monty python circus performence(the projectile stuff)?",
        "tags": "python"
    }
    }
]

1 个答案:

答案 0 :(得分:0)

您可以传递相关对象的主键:

"fields": {
    "question": "what is cryptography in computer science?",
    "tags": "computer science, cryptography.",
    "user': 1
}

或者如果您的相关类定义了“自然键”,则可以使用该字段的值。

在这种情况下,User模型定义了一个名为natural_key的{​​{1}},因此您只需传递username

username

修改 - 参考:https://docs.djangoproject.com/en/1.5/topics/serialization/#natural-keys