[Fixed]-Django: cretae new object with unique order

1👍

Because you have a lot of records to process, I would not use a recursive method on the actual Django objects. It will take too much time. But I would override the save method, before saving the object and use an SQL command.

UPDATE Example SET order = order + 1 WHERE order >= 6.

Also remember to handle the delete situation of the object in order 6, after you delete the object.

UPDATE Example SET order = order - 1 WHERE order > 6.

Edit 1:

Django has an expression called F() docs. You can use it in you case like this:

from django.db.models import F 
Example.objects.filter(order__gte=self.order).update(order=F('order')+1)

Through this Django creates an update query, which is executed. It doesn’t hit the database for every object.

Edit 2:
For example:

class Example(models.Model):
    name = models.CharField(max_length=255, blank=False, null=False)
    order = models.PositiveIntegerField(blank=False, null=False, unique=True)

    class Meta:
        ordering = ['order']

    def save(self, *args, **kwargs):
        from django.db.models import F
        Example.objects.filter(order__gte=self.order).update(order=F('order') + 1)
        super(Example, self).save(*args, **kwargs)

0👍

you have to override to save method in model, if your order number is 6 you have to pull all the records from 6 to n where n is the highest order number, you have to increment +1 to the existing order number from n to 6 in reverse order once is done now u can save for the new object with order number 6

👤rsb

Leave a comment