02. xadmin的过滤器queryset()
需求: 每个老师都只能看到自己的课程
# models.py
from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
......
class Courses:
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
class Teacher:
# 由于是中途才添加的user外键,所以当前teacher表已经存在数据,此时最好设置为SET_NULL
user=models.OneToOneField(UserProfile, null=True, blank=True, on_delete=models.SET_NULL)
# adminx.py
import xadmin
from apps.courses.models import Courses
class CoursesAdmin:
list_display = ['name', 'desc', ... ]
search_fields = ['name', 'desc', ... ]
list_filter = ['name', ...]
# 重写queryset()
def queryset(self):
# 取出当前Courses表单的所有对象
qs = super().queryset()
# 如果不是超级管理员,就对qs进行过滤
if not self.request.user.is_superuser:
# 对于OneToOne这种外键,可直接反向取user.teacher
qs = qs.filter(teacher=self.request.user.teacher)
return qs
xadmin.site.register(Courses, CoursesAdmin)
---end---