在Django admin中使用父模型值自定义下拉值

时间:2013-01-11 22:23:35

标签: django django-models django-forms django-admin

我在Django中的模型很少:

from django.db import models

class First(models.Model):
    first_name = models.CharField('First Name', max_length=100)
    first_value = models.IntegerField('Value')

    def __unicode__(self):
        return self.first_name 

class Second(models.Model):
    first_ref = models.ForeignKey(First)
    second_name = models.CharField('Second Name', max_length=100)
    second_value = models.IntegerField('Second Value')

    def __unicode__(self):
        return self.second_name

class Third(models.Model):
    second_ref = models.ForeignKey(Second)
    third_name = models.CharField('Third Name', max_length=100)
    third_value = models.IntegerField('Third Value')

    def __unicode__(self):
        return self.third_name

现在,当我尝试在我的Django管理员中为Third模型添加新记录时,我的<select>框中填充了second_name个值。如何从两个“父”表中显示不同值的串联字符串,例如first_name + first_value + second_name + second_value

1 个答案:

答案 0 :(得分:1)

只需更新unicode型号的second方法:

class Second(models.Model):
    first_ref = models.ForeignKey(First)
    second_name = models.CharField('Second Name', max_length=100)
    second_value = models.IntegerField('Second Value')

    def __unicode__(self):
        return '%s %s %s %s' % (
            self.first_ref.first_name, self.first_ref.first_value,
            self.second_name, self.second_value)