如果请求数据不在queryset中,则查看权限

时间:2014-08-05 02:10:54

标签: python django django-rest-framework

我有以下观点 -

class File_List(generics.ListAPIView):
    model = cdx_composites_csv
    serializer_class = cdx_compositesSerializer

    def get_queryset(self):
        """
        This view should return a list of all the purchases for
        the user as determined by the username portion of the URL.
        """
        filename = self.request.GET.get('filename')
        model = get_model('markit', filename)
        filedate = self.request.GET.get('filedate')
        queryset = model.objects.using('markitdb').filter(Date__contains=filedate)
        return queryset

现在忽略该模型被列出两次,这是我需要稍后解决的相同模型。

对于权限,如果发生以下情况,我希望它拒绝访问。

我的models.py

中有一个扩展的Auth
class FileIndex(models.Model):
    filename = models.CharField(max_length=256)
    filetype = models.CharField(max_length=16)
    vendorid = models.IntegerField()
    vendorname = models.CharField(max_length=256)
    tablename = models.CharField(max_length=256)
    class Meta:
        db_table = 'file_index'
        verbose_name = 'File/Vendor Index'
        verbose_name_plural = 'File/Vendor Indicies'
    def __str__(self):
        return self.filename

class UserFile(models.Model):
    userid = models.ForeignKey(User)
    fileid = models.ForeignKey(FileIndex)
    grant_date = models.DateTimeField()
    revoke_date = models.DateTimeField(blank=True)
    class Meta:
        db_table = 'auth_files'
        verbose_name = 'User File Matrix'
        verbose_name_plural = 'User File Matricies'

我希望能够说,如果文件名没有显示与用户的访问权限将被拒绝。

在SQL中,只需返回用户有权访问的文件名列表 -

select * from auth_files af
inner join auth_user au on au.id = af.userid
inner join file_index fi on fi.id = af.fileid
where au.user = 'user logged in'

然后我想告诉它,如果请求中的文件名在上面查询返回的文件名列表中,那么用户可以做他们想做的事情。

更新 - 像这样调整 -

class File_List(generics.ListAPIView):
    model = cdx_composites_csv
    serializer_class = cdx_compositesSerializer

    def get_queryset(self):
#        authorized_files = UserFile.objects.filter(userid=self.request.user).values_list('fileid')
        """
        This view should return a list of all the purchases for
        the user as determined by the username portion of the URL.
        """
        filename = self.request.GET.get('filename')
        model = get_model('markit', filename)
        filedate = self.request.GET.get('filedate')

        if FileIndex.objects.filter(filename=filename).exists():
            queryset = model.objects.using('markitdb').filter(Date__contains=filedate)
            return queryset

我现在收到以下错误 -

'NoneType' object is not iterable

1 个答案:

答案 0 :(得分:1)

在您的视图中,您可以这样检查:

filename = self.request.GET.get('filename')
if FileIndex.objects.filter(filename=filename).exists():
    #do something