Django 21-Optimize the title display of table data

I. Introduction

The default display data format of the title of each table data in each data table in the admin management background is [model class name object (primary key name)] such as [Person object(9)];

But the data format displayed by default like this, if we feel less intuitive and want to change it to the data format we want to display, we can change the content of the code block in the relevant model class to optimize;

 detail:

①. We select the model class [Person] to perform the next related operations;

 

2. The default data format displayed by the title of the table data is related information of [model class name object (primary key name)]

detail:

①. The latest code content of the model class [Person] at this time is as follows:

# 新增一张人类表,表名为hello_person,有两个表字段:name,age,表字段name数据类型是字符串类型,表字段age数据类型是int类型。
class Person(models.Model):

    name = models.CharField(max_length=30)  # 后续会对应生成一个表字段name

    age = models.IntegerField()             # 后续会对应生成一个表字段age

 ②. The code content of the method [__str__] in the parent class [models.Model] is as follows:

3. The data format displayed in the title of the optimized table data is the relevant complete operation steps of [change to the data format we want to display]

1. The first step: modify the code content of the model class [Person]

detail:

①. The return value of the special method [__str__] in the model class must meet 2 points:

    ⑴. The data type of the return value must be str;

    ⑵. The return value cannot contain Chinese, otherwise an error will be reported when adding or editing table data; (I have debugged it, and the return value does not contain Chinese)

# 新增一张人类表,表名为hello_person,有两个表字段:name,age,表字段name数据类型是字符串类型,表字段age数据类型是int类型。

class Person(models.Model):

    name = models.CharField(max_length=30)  # 后续会对应生成一个表字段name

    age = models.IntegerField()             # 后续会对应生成一个表字段age



    def __str__(self):

        return "hello_person(table)" + ":id->" + str(self.id)

detail:

①. The above operation actually rewrites the code content of the method [__str__] in the parent class [models.Model] in the subclass [Person];

2. Step 2: Restart the service of the django project [helloworld]

3. Step 3: Re-login to the admin management background successfully

4. Step 4: View the data format displayed by the title of the successfully optimized [hello_person] table data

Guess you like

Origin blog.csdn.net/LYX_WIN/article/details/114580492