2012-10-20 41 views
6

Tôi khá mới đối với Django & Tastypie. Tôi chỉ muốn trả lại một trong các đối tượng từ truy vấn. Tôi đã thử hầu hết mọi thứ và dường như không thể tìm ra giải pháp. Đây là mã của tôi dưới đây:Thực hiện đúng 'obj_get' trong Django Tastypie là gì?

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']) 

Bây giờ là phần tôi đang gặp rắc rối với là làm thế nào tôi có thể trả về một đối tượng người dùng duy nhất từ ​​một nguồn duy nhất sử dụng request.user.

Trả lời

4

Nếu bạn chỉ muốn hiển thị một tài nguyên tôi có lẽ sẽ tạo ra cái nhìn tài nguyên mới (đặt tên như my_profile) mà sẽ gọi xem chi tiết bình thường với người dùng trong kwargs và loại bỏ các url khác:

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) 
+0

này là hoàn hảo! Cảm ơn bạn rất nhiều! :) – noahandthewhale

+0

OMG. Cảm ơn bạn rất nhiều. Tôi đã tìm kiếm điều này hàng giờ liền. – Max

Các vấn đề liên quan