简体   繁体   中英

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

I have a model

class Project(models.Model):
    STATUS_CHOICE= (('going_on','GOING_ON'),
                    ('project_co','PROJECT_COMPLETED'),
                    ('contract_c','CONTRACT_COMPLETED'),
                    ('contract_e','CONTRACT_EXTENDED'),
                    )
    title= models.CharField(max_length=30,unique=True)
    description= models.CharField(max_length=2000,null=True,blank=True)
    assigned_date= models.DateField(null=True, blank=True)
    completion_date= models.DateField(null=True, blank=True)
    join_date= models.DateField(null=True, blank=True)
    technology= models.ForeignKey(Technology,null=True, blank=True)
    consultant= models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'project')
    status= models.CharField(max_length= 10, choices= STATUS_CHOICE, default= 'pending')
    file=models.FileField(upload_to=get_attachment_file_path,null=True,blank=True)
    history = HistoricalRecords()

Now I want to keep track of all changes in this project model.

I have used django-simple-history .

But it provides limited features.I know I can use signals in Django. But I have to send Historical data in such a way that how many projects have been done by a specific user with the respective STATUS_CHOICE of that project.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM