I'm working with some simple django-tastypie Resources with the following problem:
Imagine I'm building a simple rating system. I have a resource, call it Rating
that has both a User
and a Comment
. Each user has at most one rating per comment.
I'd like to make a generic resource that takes a tuple ('user', 'comment')
. Then, whenever I do a POST with a new Rating
, I'd like it to check the user
and comment
fields to see if a rating matching both of those fields already exists. If it does, overwrite the existing resource, otherwise create a new resource (so that any API call will always pass Django's unique_together).
I'm working with obj_get
as a starting point, but having difficulty understanding how to properly override it to get this behavior.
Following the discussion on IRC in #tastypie
:
It's recommended not to alter standard API behavior, as this can be dangerous in the sense that the clients will not see consistent behavior across the API.
One solution is to let Tastypie return a 4xx response when trying to create the Rating
, and in this case the client would PATCH
the existing rating.
If, however, the performance boost is really necessary, you should only alter the behavior if the client formally asks for this. Which in your case would mean adding a replace_existing_rating=True
parameter to the POST
request.
So in your case, if you did decide you need the performance boost, you could:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With