【问题标题】:How to edit POST in resources.py with DJANGO-TASTYPIE如何使用 DJANGO-TASTYPIE 在 resources.py 中编辑 POST
【发布时间】:2016-09-17 22:45:25
【问题描述】:

我正在尝试根据 POST 中的数据计算我的 django 模型中的一个字段。例如,我的 Person 模型包含诸如年龄、身高、体重、性别和 BMI 等字段,而我的views.py 具有根据其他字段计算 BMI 的函数。

问题

我如何计算resources.py 中的 BMI 与在视图中计算的相同,并将该 BMI 值添加到 POST 对象?

例如,给定这篇文章,创建一个具有以下 ageheightweightgender 的 Person > 以及后端计算的 BMI。

通常,此帖子会创建一个 BMI 为空的人。

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"age": "45", "height": "60, "weight": "130", "gender": "Female"}' http://localhost:8000/api/v1/person/

注意

这只是一个类似于我的实际代码的示例。在我的例子中,用户无法像 BMI 一样轻松计算该字段。

【问题讨论】:

    标签: python django api post tastypie


    【解决方案1】:

    也许您正在寻找的是编辑您的 ModelResource 并在 POST 之后返回 BMI 值。尝试创建这样的资源:

    from tastypie.resources import ModelResource
    from tastypie.utils import trailing_slash
    
    
    class PersonResource(ModelResource):
    
        class Meta:
            resource_name = 'lol'
            allowed_methods = ['post']  # note that this resource just accept posts
    
        def base_urls(self):
            return [
                url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('bmi_api_function'), name="api_lol_api_function"),
            ]
    
        def bmi_api_function(self, request, **kwargs):
            deserialized = self.deserialize(
                request, request.body,
                format=request.META.get('CONTENT_TYPE', 'application/json')
            )
            age = deserialized['age']  # all your post data will be at deserialized variable
            # you function
            bmi = 2 * age
            return self.create_response(request, {'bmi': bmi})
    

    希望对你有用

    【讨论】:

      猜你喜欢
      • 2014-10-26
      • 2012-01-28
      • 2011-11-01
      • 2016-01-12
      • 2012-04-25
      • 1970-01-01
      • 2013-04-03
      • 2022-11-25
      • 2013-01-15
      相关资源
      最近更新 更多