在Django的loaddata中设置foreignkeys

时间:2015-11-05 20:42:37

标签: json django python-2.7 django-models

我已经设置了两个类,其中用户可能有多个访问键。

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

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

[
{
    "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
}
]

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

非常感谢!

1 个答案:

答案 0 :(得分:1)

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

<profiles>
    <profile>
        <id>production</id>
        <activation>
            <activeByDefault>false</activeByDefault>
        </activation>
        <properties>
            <env>production</env>
        </properties>
    </profile>
    <profile>
        <id>developer</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <env>developer</env>
        </properties>
    </profile>
</profiles>

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>props/**/*.properties</exclude>
            </excludes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources/props/${env}</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
    ..........
</build>