exclude some fields in tastypie post data

馋奶兔 提交于 2020-01-15 10:29:31

问题


recently i start an API for my project by django-tastypie. actually I want to exclude some field requirement in post requests.

Assume that my model have four fields and all of them defined as require in django model. But I want to receive two of them from API request and 2 others will be filled by my functions.

So, how could I tell to tastypie to receive just those two fields and skip others?


回答1:


If you want to exclude same fields you can do that by define it in the meta class of the Resource, for example:

class MyResource(ModelResource):
     class Meta:
         excludes = (field1, field2)

And those fields will be excluded every time for this resource.

But if you want only on post to get different fields the way how I am doing that is by overriding dehydrate method:

def dehydrate(self, bundle):
     if bundle.request.META['REQUEST_METHOD'] == 'POST':
         bundle.data = dict(my_field1=bundle.obj.my_func1(),
                            my_field2=bundle.obj.my_func2()
                            )
     return bundle


来源:https://stackoverflow.com/questions/16010366/exclude-some-fields-in-tastypie-post-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!