acquayefrank
acquayefrank

Reputation: 524

Count field in django?

Lets say I have a model

class Entity(models.Model)
    count = models.IntegerField()'

Question: Is there a field type in django that can help me increase the value of count anytime an action is taken. I'm currently thinking of updating the value every-time. But I feel that might not be efficient since this involves reading the current value then increasing by one

Upvotes: 1

Views: 869

Answers (1)

Platinum Azure
Platinum Azure

Reputation: 46233

I'm not sure about if there are any model fields that will help, but you can prevent the extra database operation using an F()-expression:

# Given this model class:
class Entity(models.Model):
    count = models.IntegerField()

# Increment like this:
entity_qs = Entity.objects.filter(pk=some_pk)     # Note: This does not fetch!
entity_qs.update(count=F('count')+1)              # Single SQL update statement

Upvotes: 3

Related Questions