如何在Django模型实例中连接2个属性以创建名称?

我有一个模型:

class Subject(models.Model):
    level = models.CharField(choices=LEVEL_CHOICES, max_length=2)
    subject_name = models.CharField(max_length=50)
    teacher_name = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    total_seats = models.IntegerField()
    subject_details = models.CharField(max_length=100)
    subject_img = models.ImageField()

I want to display each instance as level and then subject name. For example, if the instance has a level 'Advanced' and subject_name as 'Physics', I want the instance to be displayed as 'Advanced Physics'.

I have tried using str method but it shows subject_name is not defined:

def __str__(self):
        return self.level+ ''+ subject_name

编辑:

I forgot to mention that level field takes in choices, as so:

LEVEL_CHOICES = (
    ('09', 'Class 9 O level'),
    ('10', 'Class 10 O level'),
    ('11', 'AS level'),
    ('12', 'A2 level'),
)

How do I display the data that is visible to human? ie. the ones on the right as the level

评论
  • XXOO
    XXOO 回复

    These are attributes defined on the self object, so you implement this as:

        def __str__(self):
            return self.level + '' + self.subject_name

    或者您也可以在这里使用字符串格式:

        def __str__(self):
            return f'{self.level}{self.subject_name}'

    If you want to use the display value for the choice of level, you can call the get_level_display method:

        def __str__(self):
            return self.get_level_display() + '' + self.subject_name
  • 莫小言
    莫小言 回复

    You need to refer to self to access subject_name as such:

    def __str__(self):
            return self.level + ' ' + self.subject_name
    

    或通过Python3格式化:

    def __str__(self):
            return '{0} {1}'.format(self.level, self.subject_name)
    

    and to get the human readable value, you can simply use the .get_FOO_display() method:

    def __str__(self):
            return '{0} {1}'.format(self.get_level_display(), self.subject_name)
    

    Model.get_FOO_display(): https://docs.djangoproject.com/en/3.0/ref/models/instances/#django.db.models.Model.get_FOO_display