【问题标题】:Setting up foreignkeys in loaddata for Django在 Django 的 loaddata 中设置外键
【发布时间】:2016-02-06 20:50:53
【问题描述】:

我设置了两个类,其中一个用户可能有多个访问密钥。

class User(models.Model):
    first_name = models.CharField(max_length=50)
    middle_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField()
    password = models.CharField(max_length=50)
    birthday = models.DateField()

    def __str__(self):
        return self.first_name+" "+self.last_name

class pets(models.Model):
    user = models.ForeignKey('User')
    type = models.CharField(max_length=50)
    color = models.CharField(max_length=50)

    def __str__(self):
        return self.type

我正在尝试通过一个 json 文件使用 loaddata 将数据预加载到表中,如下所示:

[
{
    "fields": {
        "first_name": "John",
        "last_name": "Doe",
        "middle_name": "G",
        "birthday": "1900-07-21",
        "password": "goforit123",
        "email": "John.Doe@gmail.com"
        },
        "model": "account_data.user",
    "pk": 1
},
{
    "fields": {
        "user": "????"
        "type": "dog",
        "color": "blue"
    },
    "model": "account_data.pets",
    "pk": 1
}
]

我在宠物类的用户中放了什么?

非常感谢!

【问题讨论】:

    标签: json django python-2.7 django-models


    【解决方案1】:

    您只需要使用您要链接的对象的de pk:

    [
    {
        "fields": {
            "first_name": "John",
            "last_name": "Doe",
            "middle_name": "G",
            "birthday": "1900-07-21",
            "password": "goforit123",
            "email": "John.Doe@gmail.com"
        },
        "model": "account_data.user",
        "pk": 1  // This is the pk you have to use
    },
    {
        "fields": {
            "user": 1,  // Use the pk, in this case you're referencing to John Doe
            "type": "dog",
            "color": "blue"
        },
        "model": "account_data.pets",
        "pk": 1
    }
    ]
    

    【讨论】:

    • 假设用户已经加载并且您不知道 pk。有没有办法找到它?
    • 不在这里,您不会在 JSON 文件中应用逻辑。请记住,这是加载初始/测试数据,因此,如果您有以前的用户,请将它们添加到此 JSON 文件中。
    • 但是有没有办法在 .py 文件中编写代码来查找外键,然后使用适当的 pk 生成 .json?
    • 当然,您可以创建一个custom command,例如:python manage.py find_pks,然后编写一些代码来探索您的数据库并在那里编写一个 JSON 文件。
    猜你喜欢
    • 2014-02-04
    • 2018-08-17
    • 2016-05-21
    • 2011-02-20
    • 2020-10-04
    • 2015-08-22
    • 2010-10-02
    相关资源
    最近更新 更多