2016-05-20 1 views
1

POSTのデータに基づいて私のdjangoモデルのフィールドの1つを計算しようとしています。たとえば、Personモデルに年齢、身長、体重、性別、BMIなどのフィールドがあり、views.pyには他のフィールドに基づいてBMIを計算する関数があります。DJANGO-TASTYPIEでresources.pyのPOSTを編集する方法

質問

は、どのように私はそれがビューで計算しています同じresources.pyにBMIを計算し、POSTオブジェクトにそのBMI値を中に追加することができますか?例えば

は、このポストを与えられ、バックエンドで計算し、次の年齢高さ重量性別とも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と同じ方法でユーザーが簡単に計算することはできません。

答えて

0

あなたが探しているのは、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}) 

は、それはあなた

のために働くホープ
関連する問題