django test 草稿
model
Foreignkey
反向操作
g2=Grade.objects.filter(id=2).first() g2.student_set.create(sname='s3',gender=False)
Admin管理后台
后台注册由grade添加student (不实用,条目多时比较乱)
from django.contrib import admin # Register your models here. from .models import Grade,Student class StudentInfo(admin.TabularInline): model = Student extra = 2 class GradeAdmin(admin.ModelAdmin): inlines = [StudentInfo] list_display = ['gname','ginfo'] class StudentAdmin(admin.ModelAdmin): list_display = ['sname','gender'] admin.site.register(Grade,GradeAdmin) admin.site.register(Student,StudentAdmin)
函数处理布尔值,将gender显示对应中文
原admin
class StudentAdmin(admin.ModelAdmin): list_display = ['sname','gender']
改为
class StudentAdmin(admin.ModelAdmin): def gendershow(self): if self.gender: return "男" else: return "女" list_display = ['sname',gendershow]
列名中文,用函数
class StudentAdmin(admin.ModelAdmin): def gendershow(self): if self.gender: return "男" else: return "女" gendershow.short_description = '性别' def snameshow(self): return self.sname snameshow.short_description='姓名' list_display = [snameshow, gendershow]
注册方式修改
由 admin.site.register(Student,StudentAdmin) 改为 @admin.register(Student) class StudentAdmin(admin.ModelAdmin): 。。。。略