How can I get Django-Tastypie to override a resource if it already exists?

I am working with some simple django-tastypie resources with the following problem:

Imagine that I am building a simple rating system. I have a resource, name it Rating , which has both User and Comment . Each user has no more than one rating per comment.

I would like to create a shared resource that takes a tuple ('user', 'comment') . Then, whenever I do a POST with a new Rating , I would like it to check the User and Comment fields to see if there is a rating corresponding to both of these fields. If so, overwrite the existing resource, otherwise create a new resource (so any API call will always pass Django unique_together ).

I am working with obj_get as a starting point, but I hardly understand how to properly override it to get this behavior.

+6
source share
1 answer

After discussing the IRC in #tastypie :

It is recommended that you do not change the standard behavior of the API, as this can be dangerous in the sense that clients will not see consistent behavior in the API.

One solution is to allow Tastypie to return a 4xx response when trying to create a Rating , in which case the client will PATCH existing rating.

If, however, a performance improvement is really necessary, you should only change the behavior if the client formally asks for it. Which in your case would mean adding the replace_existing_rating=True parameter to the POST request.

So, in your case, if you decide that you need to increase productivity, you can:

 class CommentResource(ModelResource): def obj_create(self, bundle, request=None, **kwargs): if bundle.data.get("replace_existing_rating", False): try: bundle.obj = self._meta.object_class._default_manager.get(**conditions) except self._meta.object_class.DoesNotExist: bundle.obj = self._meta.object_class() 
+6
source

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


All Articles