有没有办法让用户只在 django 管理的模型中查看与他相关的对象?
Is there a way to make a user only view related objects to him in a model in django administration?
我是 django 的新手,我正在尝试完全在 django 管理中制作一个学校网络应用程序。
我想做的是为学生授予权限,使他们能够只看到 scores
,其 student
字段与学生用户相同。
这是我的学生模型:
class Student(models.Model):
student_name = models.CharField(max_length=12)
student_last_name = models.CharField(max_length=12,null=True)
student_age = models.PositiveSmallIntegerField(null=True)
student_class = models.ForeignKey(Clas,on_delete=models.SET_NULL,null=True)
student_idnum = models.CharField(max_length=15,null=True)
user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.student_name
这是我的学生分数模型:
class Score(models.Model):
exam = models.ForeignKey(Exam,on_delete=models.SET_NULL,null=True)
student = models.ForeignKey(Student, on_delete=models.CASCADE,null=True)
score = models.FloatField(null=True)
def __str__(self):
return str(self.score)
我已经看到了 Meta
模型,我应该将其用于自定义权限,但我真的不知道我该怎么做。
official docs 有一个可以满足您要求的示例。
The get_queryset method on a ModelAdmin returns a QuerySet of all model instances that can be edited by the admin site. One use case for overriding this method is to show objects owned by the logged-in user
from django.contrib import admin
class MyModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(author=request.user)
admin.site.register(MyModel, MyModelAdmin)
您可以更改查询集以满足您的需要。
我是 django 的新手,我正在尝试完全在 django 管理中制作一个学校网络应用程序。
我想做的是为学生授予权限,使他们能够只看到 scores
,其 student
字段与学生用户相同。
这是我的学生模型:
class Student(models.Model):
student_name = models.CharField(max_length=12)
student_last_name = models.CharField(max_length=12,null=True)
student_age = models.PositiveSmallIntegerField(null=True)
student_class = models.ForeignKey(Clas,on_delete=models.SET_NULL,null=True)
student_idnum = models.CharField(max_length=15,null=True)
user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True)
pub_date = models.DateTimeField("date published")
def __str__(self):
return self.student_name
这是我的学生分数模型:
class Score(models.Model):
exam = models.ForeignKey(Exam,on_delete=models.SET_NULL,null=True)
student = models.ForeignKey(Student, on_delete=models.CASCADE,null=True)
score = models.FloatField(null=True)
def __str__(self):
return str(self.score)
我已经看到了 Meta
模型,我应该将其用于自定义权限,但我真的不知道我该怎么做。
official docs 有一个可以满足您要求的示例。
The get_queryset method on a ModelAdmin returns a QuerySet of all model instances that can be edited by the admin site. One use case for overriding this method is to show objects owned by the logged-in user
from django.contrib import admin
class MyModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super().get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(author=request.user)
admin.site.register(MyModel, MyModelAdmin)
您可以更改查询集以满足您的需要。