Search code examples
pythondjangodjango-database

how do increment all column values in db table after certain integer values in that column (django)?


Suppose I have created "X" database table in Django which has column id(autofiled), name(charfield) and occurrence(integerfield), now suppose 3 rows are already available in it

id name occurrence
1 ABC 1
2 BCD 2
3 CDE 3

I want to get data based on (ordering) the occurance number, I am facing a problem that, I want to add a row with an occurrence number 2 (already present), and all the rows with occurrence numbers greater than 2 update and increment automatically. (Basically, It is a inserting data on index number, where value is name and index is occurrence ignore id). For Example-

id name occurrence
1 ABC 1
2 BCD 3
3 CDE 4
4 XYZ 2

Thanks in advance.


Solution

  • class FooBar(models.Model):
        occurrence = models.IntegerField()
        name = models.CharField(max_length=100)
    
        def save(self, *args, **kwargs):
            same_occurrence = FooBar.objects.filter(occurrence=self.occurrence).first()
            if same_occurrence:
                same_occurrence.occurrence = self.occurrence + 1
                same_occurrence.save()
            return super(FooBar, self).save(*args, **kwargs)