来自 list_values 的 Django Admin 动态下拉列表

Django Admin dynamic drop down list from 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 的选择是使用 Field.choices 方法静态定义的,这在 Django Admin 中显示为一个 drop显示四个选项的下拉列表。

我真正想要的是根据以下概念动态定义选择列表,该概念基本上是 "from the Name model/table return a list of all values found in the 'device_type' column":

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)

现在您会在我的设备模型中看到我有两个外键。我需要 Location 成为 ForeignKey,因为我想将 Devices 明确地放在特定 Location 下。根据我之前的问题,我需要设备类型 ForeignKey。当我有两个这样的外键时,当我在 Django Admin 中转到我的设备 table 时,我看不到任何设备(即使它们在我创建 device_type 外键之前位于 table 中。如果我注释掉 device_type ForeignKey 并取消注释最后一行以返回到我之前的状态(在使用 'makemigrations' 和 'migrate' 更新模式后,现在设备再次显示。显然,我需要这些设备显示在我的设备中 table。我可以拥有多个外键吗?我确定我没有理解这里的关键内容。

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

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

希望对你有帮助。