【问题标题】:What is the proper implementation of 'obj_get' in Django Tastypie?Django Tastypie 中“obj_get”的正确实现是什么?
【发布时间】:2012-10-20 16:43:41
【问题描述】:

我对 Django 和 Tastypie 还很陌生。我想只返回查询中的一个对象。我几乎尝试了所有方法,但似乎找不到解决方案。下面是我的代码:

class ProfileResource(ModelResource):
     person = fields.ForeignKey(UserResource, 'user', full=True)

class Meta:
    queryset = Person.objects.all()
    resource_name = 'profile'
    authentication = BasicAuthentication()
    authorization = DjangoAuthorization()
    serializer = Serializer(formats=['json'])

现在我遇到的问题是如何使用 request.user 从单个资源返回单个用户对象。

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    如果您只想显示一个资源,我可能会创建新的资源视图(命名为 my_profile),它会在 kwargs 中调用普通的详细视图并删除其他 url:

    from django.conf.urls import url
    from tastypie.utils import trailing_slash
    class ProfileResource(ModelResource):
        ...
        def base_urls(self):
            return [
                url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_my_profile'), name="api_dispatch_my_profile")
            ]
    
        def dispatch_my_profile(self, request, **kwargs):
            kwargs['user'] = request.user
            return super(ProfileResource, self).dispatch_detail(request, **kwargs)
    

    【讨论】:

    • 这太完美了!太感谢了! :)
    • 天啊。太感谢了。我已经找了好几个小时了。
    猜你喜欢
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 2011-11-06
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多