【问题标题】:Django tastypie relative querysetDjango sweetpie 相关查询集
【发布时间】:2016-11-08 02:08:51
【问题描述】:

这是模型:

class Project(models.Model):
    creator = models.ForeignKey(User)
    name = models.CharField(max_length=64)

    def __unicode__ (self):
        return self.name

现在我想通过 REST/tastypie 获取用户项目。 我通过这样的教程制作了资源类:

class ProjectResource(ModelResource):
    class Meta:
        queryset = Project.objects.all()
        resource_name = 'project'

但此代码会为每个用户返回所有数据。

我知道如何添加身份验证,但我不明白如何根据记录的用户 ID 返回不是所有项目,而是该数据的一些子集。

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    您可以覆盖get_object_list

    class ProjectResource(ModelResource):
        class Meta:
            queryset = Project.objects.all()
            resource_name = 'project'
    
        def get_object_list(self, request):
            qs = super().get_object_list(request)
            return qs.filter(creator=request.user)
    
        def authorized_read_list(self, object_list, bundle):
            return object_list.filter(creator=bundle.request.user.id)
    

    【讨论】:

    • 哦,谢谢!为了以后节省fols时间,还有authorized_read_list函数……
    • @KaronatoR 如果您有更合适的答案,请编辑我的答案,我接受您的改进
    猜你喜欢
    • 2013-03-27
    • 1970-01-01
    • 2016-09-03
    • 2012-02-20
    • 2014-09-04
    • 2022-12-18
    • 2015-09-02
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多