2012-11-02 2 views
3

내 게시물 메서드에서 'owner'필드를 현재 사용자 (BasicAuthentication을 사용하고 있습니다)로 자동 채 웁니다. 나는 여기 코드 중 일부를 따랐다 : How to get authorized user object in django-tastypie -하지만 아직 제대로 작동하지 않았다.Django Tastypie - 현재 사용자 자원을 자동으로 선택합니다.

resources.py :

class QuestionResource(ModelResource): 
    owner = fields.ForeignKey(UserResource, 'owner') 
    class Meta: 
     queryset = Question.objects.all() 
     allowed_methods = ['get','post'] 
     fields = ['title','type'] 
     resource_name = 'question' 
     include_resource_uri = True 
     serializer = PrettyJSONSerializer() 
     authentication = BasicAuthentication() 
     authorization = Authorization() 

    def obj_create(self, bundle, request=None, **kwargs): 
     bundle = self.full_hydrate(bundle, request) 
     return bundle 

    def obj_update(self, bundle, request=None, **kwargs): 
     bundle = self.full_hydrate(bundle, request) 
     return bundle 

    def full_hydrate(self, bundle, request=None): 
     bundle = self.hydrate(bundle, request) 
     return bundle 

    def hydrate(self, bundle, request=None): 
     bundle.obj.owner = User.objects.get(pk = request.user.id) 
     return bundle 

나는 다음과 실행하면 :

curl -u USERNAME:XXXXXXX --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -X POST --data "{\"title\":\"my new question\",\"type\":\"multichoice\"}" http://localhost/python/mquiz/api/v1/question/ 

내가 응답을 얻을 : 그것은 모든 일했다 것처럼

HTTP/1.1 201 CREATED 
Date: Fri, 02 Nov 2012 08:28:05 GMT 
Server: Apache/2.2.22 (Ubuntu) 
Vary: Accept-Language,Cookie,Accept-Encoding 
Location: http://localhost/python/mquiz/api/v1/question/None/ 
Content-Language: en-us 
Content-Length: 0 
Content-Type: text/html; charset=utf-8 

그래서이 나타납니다, 하지만 데이터베이스에 아무 것도 추가되지 않고 위치가 잘못 표시됩니다 (끝에/없음/표시).

"bundle.obj.owner = User.objects.get (pk = request.user.id)"행과 관련이 있습니다. 지금까지 내가 bundle.obj.owner 양식에 있어야 말할 수

"error_message": "Cannot assign \"3L\": \"Question.owner\" must be a \"User\" instance." 

: 내가 사용하는 경우 "bundle.obj.owner = request.user.id는"그때는 오류 '/ python/mquiz/api/v1/user/3/'- 내 curl 요청에있는 데이터에서 소유자 매개 변수로 이것을 사용하면 (사용자 정의 하이드레이트 메소드를 제거함), 모든 것이 올바르게 작동하고 데이터베이스에 추가됩니다. 그렇다면 사용자 인스턴스를 허용 할 양식으로 변환하려면 어떻게해야합니까?

도움을 주시면 감사하겠습니다.

답변

1

현재 유효성이 검증 된 답변은 2 개의 SQL 쿼리가 발생하므로 차선책입니다.

당신은 오히려 다음과 같이 귀하의 검색어를 수정해야 다음 '소유자'데이터가 하나 개의 SQL 쿼리에 가입되어

queryset = Question.objects.select_related('owner').all() 

이 방법을.

+0

방금 ​​승인 된 답변으로 업데이트되었습니다. –

4

아 ... 지금 알아 냈습니다. 작동 방식 :

class QuestionResource(ModelResource): 
    owner = fields.ForeignKey(UserResource, 'owner') 
    class Meta: 
     queryset = Question.objects.all() 
     allowed_methods = ['get','post'] 
     fields = ['title','type'] 
     resource_name = 'question' 
     include_resource_uri = True 
     serializer = PrettyJSONSerializer() 
     authentication = BasicAuthentication() 
     authorization = Authorization() 


    def hydrate(self, bundle, request=None): 
     bundle.obj.owner = User.objects.get(pk = bundle.request.user.id) 
     return bundle 

request.user.id가 아니라 bundle.request.user.id가 필요했습니다. 아마도 이전 버전의 TastyPie를 참조한 다른 질문이있을 것입니다. 이전 버전은 요청에 번들로 액세스 할 수 없었던 것 같습니다.

+2

감사합니다. TastyPie 0.9.15에는'hydrate'에 대한'request' 인수가 없지만 여전히 유효합니다. 또한 메인 라인을'bundle.obj.owner = bundle.request.user'로 단축 할 수 있습니다. –

관련 문제