Search code examples
djangocountanalytics

django count instances in a model


I have a model ItemAdded and i made a signal so every time a user add an item to the cart an instance is created in the ItemAdded model so what i want to do is count the most added items (in an ascending order) , so what is the easiest way to do this ?? this is the model :

class ItemAdded(models.Model):
user                = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) # User instance instance.id

content_type        = models.ForeignKey(ContentType, on_delete=models.CASCADE) # User, Product, Order, Cart, Address
object_id           = models.PositiveIntegerField() # , Product id, 
content_object      = GenericForeignKey('content_type', 'object_id') # Product instance
timestamp           = models.DateTimeField(auto_now_add=True)



def __str__(self):
    return "%s added on %s" %(self.content_object, self.timestamp)

class Meta:
    ordering = ['-timestamp'] # most recent saved show up first
    verbose_name = 'Object added'
    verbose_name_plural = 'Objects addded'

Solution

  • If you don't care about timing creating a separate model and thousands of database rows along you can simply create an IntegerField in your model which you will increment whenever you get the signal that you mentioned. To get the result:

    models.py

    class YourItemModel(models.Model)
    
         # YourItemModel attributes
         ...
         added_count = models.PositiveIntegerField(default=0) # yes zero is accepted
    
    

    Your signal logic:

    from django.db.models import F
    
    instance.added_count = F(added_count) + 1
    instance.save()
    
    

    The F object is preferred as it eliminates racing condition when we deal with a lot of calls. You can read about it here

    PS the PositiveIntegerField accepts value of 0 due to reverse compatibility reasons