Atomic operations in Django?

后端 未结 7 1755
陌清茗
陌清茗 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条回答
  •  -上瘾入骨i
    2020-12-13 03:28

    Two suggestions:

    Add a unique_together to your model, and wrap the creation in an exception handler to catch duplicates:

    class VisitorDayTypeCounter(models.Model):
        visitType = models.CharField(max_length=60)
        visitDate = models.DateField('Visit Date')
        counter = models.IntegerField()
        class Meta:
            unique_together = (('visitType', 'visitDate'))
    

    After this, you could stlll have a minor race condition on the counter's update. If you get enough traffic to be concerned about that, I would suggest looking into transactions for finer grained database control. I don't think the ORM has direct support for locking/synchronization. The transaction documentation is available here.

提交回复
热议问题