1

我需要显示来自模型内部函数的数据。在下面的示例中,我想在 getAdult 函数中获取学生的成人。里面应该放什么??获取数据..

models.py:

    class Student(models.Model):

        name = models.CharField(max_length=255)
        age = models.IntegerField(blank=True,
                                  default=0)

        birthday = models.DateField(blank=True,
                                    null=True)
        school = models.CharField(max_length=255,
                                  blank=True,
                                  default='')
        def getAdult(self):
            try:
                adult = self.relationships.filter()[0].adult

                return adult
            except IndexError:
                return None

管理员.py:

    from django.contrib import admin
    from school.models import Student

    class StudentAdmin(admin.ModelAdmin):
        list_display=('name',??)

如果问题很愚蠢,请原谅我。

4

1 回答 1

2

您的getAdult方法应该返回一个字符串。我不确定对象adult是什么类型,所以我假设它str()会为它返回字符串表示形式。

你可以这样做:

class Student(models.Model):
#your stuff

    def getAdult(self):
        try:
            adult = self.relationships.filter()[0].adult
            return str(adult)
        except Exception:
            return ''
    getAdult.shot_description = 'Adult'

class StudentAdmin(admin.ModelAdmin):
    list_display=('name', 'getAdult')

有关更多信息,请参阅:ModelAdmin 中的 list_display

更新(如果对象没有内置字符串表示)

#example Adult model
class Adult(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    age  = models.IntegerField()

class Student(models.Model):
    #other stuff
    def getAdult(self):
        try:
            adult = self.relationships.filter()[0].adult
            return '%s %s' % (adult.first_name, adult.last_name)
        except Exception:
            return ''
    getAdult.shot_description = 'Adult'

class StudentAdmin(admin.ModelAdmin):
    list_display=('name', 'getAdult')
于 2012-08-03T07:10:52.380 回答