2015-12-04 40 views
0

名單上有以下型號:Django管理動態下拉從list_values

class Name(models.Model): 
    device_type = models.CharField('Device Type', max_length=30, blank=True, null=True) 

class Device(models.Model): 
    DEVICE_TYPE_CHOICES = (
     ('Router', 'Router'), 
     ('Switch', 'Switch'), 
     ('Firewall', 'Firewall'), 
     ('Load Balancer', 'Load Balancer'), 
    ) 
    device_name = models.CharField('Device Name', max_length=100) 
    device_type = models.CharField('Device Type', max_length=20, blank=True, null=True, choices=DEVICE_TYPE_CHOICES) 

鑑於上述情況,現在,當我用我的設備型號創建一個新的對象,DEVICE_TYPE選擇定義靜態使用現場.choices方法,這在Django Admin中顯示爲一個下拉列表,顯示了四個選項。

我真正想要的是擁有的動態定義基於以下概念,基本上說「從名稱型號/表中返回的‘DEVICE_TYPE’列中的所有值的列表」選擇該列表:

Name.objects.all().values_list('device_type') 

我只是不確定如何將其付諸實踐。我不知道如何獲取我已經知道如何從我的數據庫中獲取的列表,並將其合併到Field.objects方法中,以便這些項目在我的下拉菜單中顯示爲選項。

任何人都可以指向正確的方向嗎?預先感謝您的幫助。

更新後FOREIGN KEY FIX:

現在我的模型是這樣的:

class Name(models.Model): # device type naming standards 
    device_type = models.CharField('Device Type', max_length=30, blank=True, null=True) 
    device_alias = models.CharField('Device Alias', max_length=30, blank=True, null=True) 
    def __unicode__(self): 
     return self.device_type 

class Device(models.Model): 
    location_name = models.ForeignKey('Location') 
    device_name = models.CharField('Device Name', max_length=100) 
    device_type = models.ForeignKey('Name') 
    #device_type = models.CharField('Device Type', max_length=20, blank=True, null=True, choices=DEVICE_TYPE_CHOICES) 

現在你可以在我的設備型號見我有兩個ForeignKeys。我需要將位置作爲外鍵,因爲我想將設備分類放置在特定位置下。我需要上一個問題的設備類型ForeignKey。當我有兩個這樣的ForeignKeys時,當我進入Django Admin的Device表時,我看不到任何設備(儘管它們在創建device_type ForeignKey之前已在表中,如果我註釋掉device_type ForeignKey並取消最後一個註釋(在用'makemigrations'和'migrate'更新模式後,現在設備再次顯示出來,顯然我需要這些設備出現在我的設備表中,我允許有多個ForeignKeys ?我敢肯定,我不理解的東西在這裏是至關重要的。

回答

1

如果將使用ForeignKey的,你會得到名稱設備

device_type = models.ForeignKey('Name') 
    def __unicode__(self): 
     return self.device_type 

希望它可以幫助你的列表。

+0

OperationalError at/customers/admin/customers/device/ no such column:customers_device.device_type_id – Dan

+0

您使用的是什麼版本的django? –

+0

我已經嘗試過了,但因上面的錯誤而結束,因爲ForeignKey會自動將_id追加到字段名的末尾,然後它與數據庫中實際不匹配。另外,如果我必須添加另一個字段到我的名字模型?我如何在ForeignKey('Name')中指定一個特定的字段,因爲我試圖弄清楚,但不能。 – Dan