In django models how to update a particular column after creating

300 views Asked by At

I have models.py as below,

class members(models.Model):
    id = models.AutoField(primary_key=True)
    HID = models.IntegerField(blank=False,unique=True)
    owner = models.ForeignKey(User)
    member_name = models.CharField(max_length=25, blank=False, default='')
    father_name = models.CharField(max_length=25, blank=False, default='')
    wife_name = models.CharField(max_length=25, blank=False, default='')

Now in the above HID value is entered manually each time. When there is a new member is getting inserted I am planing to enter my previous member HID value after which the insertion should be done, so that all entries after that should be updated with HID + 1.

I tried to implement this with linked list model like having one more with next_HID= , but here the issue is my insertion is very less like yearly one or 2 but query is more so then each time this list has to be created by doing query. so I thought to update the HID number each time after insert.

Please let me know how can I run an update query after every insert in django models for the above purpose

1

There are 1 answers

10
OregonTrail On BEST ANSWER

It's as simple as this:

members.objects.filter(HID__gt=new_member_HID).order_by('-HID').update(HID=F('HID')+1)

If you are using the class-based views from Django Rest Framework, then you can add this line right below

serializer = self.get_serializer(data=request.data)

by overriding the method create of your CreateAPIView

Use the HID that's in request.data