Home > OS >  How do add 1 to the PositiveIntegerField model field when adding each new Post?
How do add 1 to the PositiveIntegerField model field when adding each new Post?

Time:10-01

I have a Posts model. And field Order = models.PositiveIntegerField() has been created for arbitrary sorting.

class Post(models.Model):
    title = models.CharField(max_length=15)
    create = models.DateTimeField(auto_now_add=True)
    Order = models.PositiveIntegerField()

Objective: in the model, overriding the save method, do add the index 1 (from the last available index of Posts) to this field when adding each new Post.

That is, each post must have an Order-index, and if there are already 3 posts on the site, then when the fourth is added - index 4 is added to his the field, and so on.

"1" index in Order field (1st post), "2" index in Order field (2nd post) etc 3, 4, 5... similar ID.

Help implement this logic im method save. It seems simple, but I don't know how to approach it.

I understand that in the model and what I do:

def save(self, *args, **kwargs):
    qs = self.order.objects.all()
    last_item = qs.latest(self.order)
    last_item.order  = 1
    super().save(*args, **kwargs)

But this don't work. Help me, please!

CodePudding user response:

Maybe something like this:

def save(self, *args, **kwargs):
    model_class = type(self)
    last_item = model_class.objects.order_by('-order').first()
    if last_item is not None:
        self.order = last_item.order  = 1

    super().save(*args, **kwargs)

You get the class (model_class), then you sort descendingly by order field and get the first instance.

I suggest you add an Index for the order field, if you don't have it already, because this field will be queried every time a new instance is created. Without indexes the performance might suffer, specially if there are many rows.

  • Related