[Answered ]-How can I provide an API to get the History of changes made in any model in django-rest?

2๐Ÿ‘

I think this can work out. It should be decently efficient, even if you have millions of rows.


models.py

from django.utils import timezone

class Change(models.Model):
     project = models.ForeignKey(Project)
     changed_field = models.CharField("field_name")
     changed_data = models.TextField() # you can improve this by storing the data in compressed format
     chaged_at = models.DateTimeField(default=timezone.now)
     status = models.CharField(max_length= 10, choices= STATUS_CHOICE, default= 'pending')

serializers.py

class ChangeSerializer(serializers.ModelSerializer):
     class Meta:
          model = Change
          fields = ("project","changed_field",# all the other fields that you wanna add)

views.py

def get_changes(request,project_id,status):
  if request.method == 'GET':  
    changes = Change.objects.filter(status=status, project=Project.objects.get(pk=project_id))
    serializer = ChangeSerializer(changes, many=True)
    return JSONResponse(serializer.data)

urls.py

urlpatterns = [
   url(r'changes/(?P<project_id>\d+)/(?P<status>[a-z]+)/',views.get_changes)
]

Let me know if you want any other changes

Leave a comment