Fields and exclude in tastypie

I would like to include some fields in the GET response and include a smaller subset of the fields in the POST confirmation response. I need to have a lot of del bundle ['field1'], del bundle ['field2'] in alter_detail_data_to_serialize for this. Is there any general way I can specify the fields and exclude for each type of request in my resource?

+4
source share
1 answer

I looked at the source of Tastypie, and my conclusion is as follows.

You can try to measure your resource and change the value of the excludes attribute on the fly when the POST method, but it will be difficult and, most importantly, to crack.

Therefore, I think that it’s best to do what you are doing, but perhaps instead of doing a few del bundle[ 'field' ] , introduce the post_excludes attribute or some of them and implement a more convenient and flexible way to get rid of these fields For example, you can do something like this:

 class YourResource( Resource ): class Meta: # ... post_excludes = [ 'foo', 'bar' ] # ... # ... def alter_detail_data_to_serialize( self, request, data ): if request.method == 'POST': data.data = { key : value for key, value in data.data.copy().iteritems() if \ key not in self._meta.post_excludes } return data # ... 

This would be cleaner and consistent with Tastypie's rules, which are important not to end with confusing, cracked code that is hard to maintain.

Hope this helps :)

+5
source

Source: https://habr.com/ru/post/1402995/


All Articles