Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up foreignkeys in loaddata for Django

I have setup two classes, where a user may have multiple access keys.

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

I am trying to preload the tables with data using loaddata through a json file that looks like:

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

What do I put in the user for the pet class?

Thanks much!

like image 340
H C Avatar asked Dec 30 '25 01:12

H C


1 Answers

You just need to use de pk of the object you want to link:

[
{
    "fields": {
        "first_name": "John",
        "last_name": "Doe",
        "middle_name": "G",
        "birthday": "1900-07-21",
        "password": "goforit123",
        "email": "[email protected]"
    },
    "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
}
]
like image 188
Gocht Avatar answered Dec 31 '25 16:12

Gocht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!