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

Time:03-15

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.

CodePudding user response:

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)

CodePudding user response:

class FooBar(models.Model):
    occurrence = models.IntegerField()
    name = models.CharField(max_length=100)

Try out this query

Foobar.object.filter(occurence__gte=sort_number).update(occurence=F('occurence') 1)
  • Related