How to write helper method for PATCH request using django-tastypie?

I have a Comment object which has a text field. For editing it’s text field, we can send a PATCH request (based on REST principles). I am using django-tastypie for REST API. Now I want to keep history of this text field, so that original text is not deleted but stored in some other object. We can make a new EditedComment model that has the old_text and new_text fields.

Now my question is how do I populate this model? I will need some helper method that on every PATCH request, creates an instance of the EditedComment model and saves it in database.

Answer

Add the obj_update method in CommentResource: (assuming a uuid field)

def obj_update(self, bundle, **kwargs):
        old_text = bundle.obj.text
        new_text = bundle.data['text']
        Comment.objects.filter(uuid=bundle.data['uuid']).update(text=new_text) # update comment
        c = Comment.objects.get(uuid=bundle.data['uuid'])
        EditedComment(cmt=c, old_text = old_text, new_text = new_text).save()
        return bundle

Leave a Reply

Your email address will not be published. Required fields are marked *