[Answered ]-How to implement this function?

1👍

You should save the item:

class Contact(models.Model):
    # …

    def get_appear(self, save=True):
        self.appearance += 1
        if save:
            self.save(update_fields=('appearance',))

or if there might be race conditions:

from django.db.models import F

class Contact(models.Model):
    # …

    def get_appear(self, save=True):
        old = self.appearance
        if save:
            self.appearance = F('appearance') + 1
            self.save(update_fields=('appearance',))
        self.appearance = old + 1

This will make a query that looks like:

UPDATE contact
SET appearance = appearance + 1
WHERE pk = pk

so if multiple queries run almost simultaneously, it will each time increment the appearance column.

0👍

Resolving by adding instance.save()

👤tarp20

Leave a comment