2012-12-18 38 views
0

使用Tastypie和Django用戶流,我試圖構建一個活動源。我已經成功地構建了功能下面加入最愛:如何檢索在Tastypie中創建的對象

class LikeResource(ModelResource): 
user = fields.ForeignKey(BasicUserResource, 'user', full=True) 
class Meta: 
    queryset = Journalist.objects.all() 
    allowed_methods = ['get', 'put'] 
    resource_name = 'like' 
    fields = ['user'] 
    default_format = "application/json" 
    authorization = Authorization() 
    authentication = BasicAuthentication() 
    serializer = Serializer(formats=['json']) 
    always_return_data = True 
    include_resource_uri = False 

def hydrate(self, bundle): 
    shot = LifeShot.objects.all().get(id = bundle.data['post id']) 
      if(bundle.obj.likes.filter(id = bundle.data['post id']).exists()): 
       bundle.obj.likes.remove(shot) 
      else: 
       bundle.obj.likes.add(shot) 
       user_doing_the_liking=User.objects.get(username=bundle.request.user.username) 
       user_getting_liked = shot.journalist.user 
       user_streams.add_stream_item(user_getting_liked, '%s liked your shot %s %s' % (bundle.request.user.username, shot.url, datetime.datetime.utcnow())) 
      return bundle 

    def dehydrate(self, bundle): 
     shot = LifeShot.objects.all().get(id = bundle.data ['post id']) 
     user_getting_liked = shot.foodie.user 
     likeitems = user_streams.get_stream_items(user_getting_liked) 
     list = '' 
     for likeitem in likeitems: 
       list = list + likeitem.content +', ' 
     bundle.data['likestream'] = list 
     return bundle 

現在對於評論中的照片,這是我到目前爲止有:

class CommentEntryResource(ModelResource): 
user = fields.ForeignKey(BasicJournalistResource, 'user', full =True) 
picture = fields.ForeignKey(BasicLifeShotResource, 'picture', full=True) 
class Meta: 
    queryset = Comment.objects.all() 
    allowed_methods = ['post', 'get','put'] 
    resource_name = 'comment' 
    fields = ['comment', 'picture', 'user'] 
    authorization = Authorization() 
    authentication = BasicAuthentication() 
    serializer = Serializer(formats=['json']) 
    include_resource_uri = False 
    always_return_data = True 

    filtering = { 
      'picture': ALL_WITH_RELATIONS, 
    } 

def hydrate_user(self, bundle): 

    bundle.data['user'] = Journalist.objects.get(user = bundle.request.user) 


    return bundle 

唯一的區別就在這裏,現在是Tastypie創造了一個新評論對象。我如何檢索該評論對象並使用Django用戶流實施它,以便在我的源中,它說「User1評論了你的鏡頭:看起來不錯!」 ???

Django的用戶流:https://github.com/dabapps/django-user-streams Tastypie:http://django-tastypie.readthedocs.org/en/latest/

回答

1

試試這個爲:

bundle.data['user'] = Journalist.objects.get(user = bundle.obj.user) 

bundle.obj會給你Comment模型對象。您可以通過bundle.obj.user獲取用戶。

+0

謝謝你回答Ahsan – noahandthewhale

+1

我很高興它可以幫助你。 – Ahsan

相關問題