2015-07-13 105 views
0

的獨特組合,我有4個Django模型:Django的外鍵

class KeyOne(models.Model): 
    name = models.CharField(unique=True) 

class KeyTwo(models.Model): 
    name = models.CharField(unique=True) 

class KeyThree(models.Model): 
    name = models.CharField(unique=True) 

class KeyList(models.Model): 
    key_one = models.ForeignKey(KeyOne) 
    key_two = models.ForeignKey(KeyTwo) 
    key_three = models.ForeignKey(KeyThree) 
    list = models.CharField() 

基本上,KeyList是的KeyOneKeyTwoKeyThree不同組合相關的關鍵字的列表。我如何確保在Django Admin中只能輸入獨特的組合?

+3

嘗試用['unique_together'](https://docs.djangoproject.com/en/1.8/ref/models/options/ #獨一無二的)在類Meta:中。 – dhke

回答

2

你必須在密鑰列表的元類設置:

class KeyList(models.Model): 
    key_one = models.ForeignKey(KeyOne) 
    key_two = models.ForeignKey(KeyTwo) 
    key_three = models.ForeignKey(KeyThree) 
    list = models.CharField() 
    class Meta: 
     unique_together = (("key_one", "key_two", "key_three"),)