我正在尝试从他关于Django Advent的文章中实现Florian的object permissions system,但是我遇到了一个问题,试图将查询集限制为只返回用户有权编辑/查看的项目。弗洛里安在他关于包装管理员的章节中提及它,但跳过它。我看不到过滤查询集的好方法。我错过了什么吗?
答案 0 :(得分:0)
执行此操作时:
class ObjectPermission(models.Model):
user = models.ForeignKey(User)
can_view = models.BooleanField()
can_change = models.BooleanField()
can_delete = models.BooleanField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
您可以通过这种方式过滤查询集(在方法查询集中):
def queryset(self, request):
qs = super(YourModelAdmin, self).queryset(request)
op = ObjectPermission.objects.filter(user=request.user, can_change=True, content_type=ContentType.objects.get_for_model(YourModel)).values_list('object_id').distinct()
qs = queryset.filter(id__in=[id[0] for id in op])
return qs