list_values

时间:2015-12-04 18:48:09

标签: django dynamic drop-down-menu django-models django-admin

我有以下型号:

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模型创建一个新对象时,使用Field.choices方法静态定义了device_type的选项,这在Django Admin中显示为一个下拉列表,其中显示了四个选项。

我真正想要的是根据以下概念动态定义选择列表,该概念基本上表示"从名称模型/表中返回在' device_type&#39中找到的所有值的列表;柱":

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

我只是不确定如何将其付诸实践。我不确定如何获取我已经知道如何从我的数据库中获取的列表并将其合并到Field.objects方法中,以便这些项目在我的下拉菜单中显示为选项。

有人能指出我正确的方向吗?提前感谢您的任何帮助。

外键修正后更新:

现在我的模型看起来像这样:

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。我需要Location是ForeignKey,因为我想将Devices明确地放在特定的位置下。根据我之前的问题,我需要设备类型ForeignKey。当我有两个像这样的ForeignKeys时,当我进入Django Admin中的Device表时,我看不到任何设备(即使它们在创建device_type ForeignKey之前就在表中。如果我注释掉device_type ForeignKey并取消注释掉最后一个回到我以前的状态(使用' makemigrations'以及'迁移'更新模式之后,现在设备再次出现。显然我需要设备出现在我的设备表。我可以拥有多个ForeignKeys吗?我确定我不理解这里的一些重要事项。

1 个答案:

答案 0 :(得分:1)

如果您将使用ForeignKey,您将获得名称设备列表

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

希望对你有所帮助。

相关问题