2015-11-05 44 views
0

我設置了兩個類,其中一個用戶可能有多個訪問鍵。在Django的loaddata中設置外鍵

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": "[email protected]" 
     }, 
     "model": "account_data.user", 
    "pk": 1 
}, 
{ 
    "fields": { 
     "user": "????" 
     "type": "dog", 
     "color": "blue" 
    }, 
    "model": "account_data.pets", 
    "pk": 1 
} 
] 

我把什麼用戶爲寵物類?

非常感謝!

回答

0

你只需要去的對象的PK使用要鏈接:

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

比方說,用戶已經加載,你不知道的PK。有沒有辦法找到它? –

+0

不在這裏,你不會在JSON文件中應用邏輯。請記住,這是加載初始/測試數據,因此,如果您有先前的用戶將它們添加到此JSON文件。 – Gocht

+0

但是有沒有辦法在.py文件中編寫代碼來查找外鍵,然後用適當的pk生成.json? –