【问题标题】:Update an object using Tastypie Django使用 Tastypie Django 更新对象
【发布时间】:2014-06-19 08:44:15
【问题描述】:

我正在尝试使用 Django 中的 Tastypie Api 更新对象,但我找不到任何方法...

我想发送一个类似 /api/vote/pk=3 的 URL,它会使用 pk=3 更新对象并增加投票数字段...可以轻松做到吗?

提前谢谢...

我只是尝试创建一个这样的资源:但即使我不执行任何过程,它也不起作用。它需要定义obj_get_list等...

class IphoneVoteRessource(Resource): 
    id = fields.IntegerField(attribute='id') 
    name = fields.CharField(attribute='name') 

class Meta: 
    resource_name = 'poi_vote' 
    object_class = Row 

def obj_update(self, bundle, request=None, **kwargs): 
    # update an existing row 
    pk = int(kwargs['pk']) 
    return bundle ` 

我已经多次使用 Tastypie 来获取数据,但从未更新过一个对象..

【问题讨论】:

  • 我只是试图创建一个这样的资源:但即使我不做任何过程它也不起作用。它需要定义 obj_get_list 等...` class IphoneVoteRessource(Resource): id = fields.IntegerField(attribute='id') name = fields.CharField(attribute='name') class Meta: resource_name = 'poi_vote' object_class= Row def obj_update(self, bundle, request=None, **kwargs): # 更新现有行 pk = int(kwargs['pk']) return bundle ` 我已经用过很多次 Tastypie 来获取数据,但从来没有更新一个对象...

标签: django api tastypie


【解决方案1】:

我终于使用了 ModelResource,如果有人想要一个可行的例子:

class VoteResourceAnonymous(ModelResource):

class Meta:
    queryset = VoteAnonymous.objects.all()
    resource_name = 'vote_object'
    # need to send 'vote_value' and 'object_id'
    excludes = ['created_at', 'content_type', 'content_object', 'user_agent', 'ip_address']
    allowed_methods = ['get', 'post', 'put', 'delete']
    always_return_data = True

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

    vote_value = bundle.data['vote_value']
    object_id = bundle.data['object_id']

    tmp_poi = PointOfInterestActivity.objects.get(id=object_id)
    content_type_object = ContentType.objects.get_for_model(tmp_poi)

    bundle.obj = VoteAnonymous(vote_value=vote_value,
                               object_id=object_id,
                               user_agent="",
                               ip_address="",
                               content_type=content_type_object,
                               )

    bundle.obj.save()

    if vote_value > 0:
        bundle.data['new_nb_votes'] = tmp_poi.nb_votes + 1
    else:
        bundle.data['new_nb_votes'] = tmp_poi.nb_votes - 1

    return bundle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多