Django admin中TabularInline和StackedInline使用

TabularInline类用于在A页面上编辑B表的字段,举例说明,如果models.py中有Staff、Job两个model:

from django.db import models
class Staff(models.Model):
     name = models.CharField(max_length=10)
class Job(models.Model):
     staff = models.ForeignKey(Staff)
     task = models.CharField(max_length=100)
class Salary(models.Model):
     staff = models.ForeignKey(Staff)
     salary = models.IntegerField(max_length=8)

如果想在Staff页面编辑Job的内容,可以在admin.py中这么写:

from django.contrib import admin
class JobInline(admin.TabularInline):
     model = Job
class StaffAdmin(admin.ModelAdmin):
     inlines = [
      JobInline,
     ]

如果想编辑第三个表,也可以直接加上,比如models.py中职员还有一个工资表Salary:

from django.contrib import admin
class JobInline(admin.TabularInline):
     model = Job
class SalaryInline(admin.TabularInline):
     model = Salary
class StaffAdmin(admin.ModelAdmin):
     inlines = [
      JobInline,
      SalaryInline
     ]

Django提供了两个InlineModelAdmin的子类,分别是TabularInline和StackedInline,区别在于使用的模板不同。

补充知识:django admin TabularInline raw_id_fields 添加查询 搜索小图标显示

posted @ 2023-03-30 15:57  super_ip  阅读(228)  评论(0编辑  收藏  举报