Atomic operations in Django?

后端 未结 7 1756
陌清茗
陌清茗 2020-12-13 03:21

I\'m trying to implement (what I think is) a pretty simple data model for a counter:

class VisitorDayTypeCounter(models.Model):
    visitType = models.CharFi         


        
7条回答
  •  粉色の甜心
    2020-12-13 03:28

    This is a bit of a hack. The raw SQL will make your code less portable, but it'll get rid of the race condition on the counter increment. In theory, this should increment the counter any time you do a query. I haven't tested this, so you should make sure the list gets interpolated in the query properly.

    class VisitorDayTypeCounterManager(models.Manager):
        def get_query_set(self):
            qs = super(VisitorDayTypeCounterManager, self).get_query_set()
    
            from django.db import connection
            cursor = connection.cursor()
    
            pk_list = qs.values_list('id', flat=True)
            cursor.execute('UPDATE table_name SET counter = counter + 1 WHERE id IN %s', [pk_list])
    
            return qs
    
    class VisitorDayTypeCounter(models.Model):
        ...
    
        objects = VisitorDayTypeCounterManager()
    

提交回复
热议问题