选择对象,然后选择与此相关的另一个对象

时间:2013-03-08 12:37:07

标签: django django-models django-admin

我很难用文字解释我需要什么,所以我这里有一些代码:

class Configuration(models.Model):
    name = models.CharField(max_length=250)
    firmware_version = models.ForeignKey(FirmwareVersion)
    devices_amount = models.PositiveIntegerField()
    def __unicode__(self):
        return unicode(self.name)

class Firmware(models.Model):
    name = models.CharField(max_length=250)
    circuit_model = models.ForeignKey(Versiiplates)
    def __unicode__(self):
        return unicode(self.name)

class FirmwareVersion(models.Model):
    firmware = models.ForeignKey(Firmware)
    version = models.CharField(max_length=100)
    file = models.FileField(upload_to="firmware/")
    upload_date = models.DateField(default = datetime.date.today())
    notes = models.TextField(max_length=2500, null=True, blank=True)
    def __unicode__(self):
        return u'%s %s' % (self.firmware.__unicode__(), self.version)

有没有办法在首先配置固件的管理员更改表单中选择,然后选择与之相关的任何FirmwareVersion?

1 个答案:

答案 0 :(得分:0)

使用django-smart-selects实现此行为非常简单。在我的情况下,Configuration类应该如下所示:

class Configuration(models.Model):
    name = models.CharField(max_length=250)
    firmware = models.ForeignKey(Firmware, related_name="firmware")
    firmware_version = ChainedForeignKey(FirmwareVersion, chained_field="firmware", chained_model_field="firmware", show_all="False", auto_choose=True)
    devices_amount = models.PositiveIntegerField()
    def __unicode__(self):
        return unicode(self.name)