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

2024-04-27 12:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如何为django模型提供初始数据,包括foreignkeys和datetimefield。你知道吗

例如:

法定人数/型号.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)

法定人数/固定装置/问题.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"
    }
    }
]

Tags: djangofrom模型fieldsmodelismodelstags
1条回答
网友
1楼 · 发布于 2024-04-27 12:24:09

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

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

或者,如果相关类定义了一个“自然键”,则可以只使用该字段的值。你知道吗

在本例中,User模型定义了一个名为usernamenatural_key,因此您可以只传递username

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

编辑-引用:https://docs.djangoproject.com/en/1.5/topics/serialization/#natural-keys

相关问题 更多 >