DEV Community

Cover image for How to track number of hits/views for particular objects in Django | Django Packages Series #2

How to track number of hits/views for particular objects in Django | Django Packages Series #2

Rashid on October 06, 2019

This post cross-published with OnePublish What's up DEVs? Welcome to the second post of Django Packages Series. In this quick tutorial we are goi...
Collapse
 
samatuulu profile image
Beka

How I can get the number views of one object in django shell?
I am getting error that says:
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'GenericRelatedObjectManager' object has no attribute 'hits'

for this error the query is: john_wick.hit_count_generic.hits

john_wick is Movie instance. And my model is

class Movie(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(max_length=2000)
image = models.ImageField(upload_to='movie_upload', null=False, blank=False)
year_of_production = models.IntegerField()
iframe = models.CharField(max_length=1500, verbose_name='iframe src')
hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk',
related_query_name='hit_count_generic_relation')
created_at = models.DateTimeField(auto_now_add=True)

Please help me figure out.

Collapse
 
soniarpit profile image
Arpit

Ok worked!! but how to test it. Initially showing 0. I opened my post but count not increase

Collapse
 
ybastan profile image
ybastan

same problem here. Still 0 (zero) count is not increasing.

Collapse
 
soniarpit profile image
Arpit
class PostDetail(HitCountDetailView):
    model = Post
    context_object_name = "post"
    template_name = "awesomeposts/post_detail.html"
    count_hit = True

    def get_object(self):
        username = self.kwargs.get("username")
        post = self.kwargs.get("post")
        return get_object_or_404(
            Post,
            user=User.objects.get(username=username),
            slug=post,
        )
Enter fullscreen mode Exit fullscreen mode

do like this

Thread Thread
 
ybastan profile image
ybastan

I don't know why but it didn't worked for me. Still 0 (zero)

Collapse
 
sajjadafridi profile image
Muhammad Sajjad

After python mange.py migrate
i get this error
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'object_pk' used in key specification without a key length")

Collapse
 
mahmudulhassan5809 profile image
Mahmudul Hassan

Did you solved this error??

Collapse
 
bos1313 profile image
bos1313

Great tutorial and it works fin with Sqlite database but when I try to use it with MySQL database I got error when do migration
150 "Foreign key constraint is incorrectly formed")')
I use user field as well
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)

Collapse
 
razilator profile image
Vladislav

To get rid of n + 1 queries, you can add the @property sum method. Namely:
class Post(models.Model):
views = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='posts')

@property
def views_num(self):
"""Подсчет просмотров"""
return sum([views.hits for views in self.views.all()])

And finally, add prefetch_related ('views') to our Manager like mine:
class PostManager(models.Manager):
"""Менеджер постов"""

def get_queryset(self):
return super().get_queryset()

def all(self):
return self.get_queryset().filter(is_published=True)\
.select_related('category', 'created_by', 'updated_by', 'game')\
.prefetch_related('comments', 'rating', 'subcategory', 'attachment', 'views')

Collapse
 
gamino97 profile image
gamino97

For those that have the error "(errno: 150 "Foreign key constraint is incorrectly formed")')", I've found an improvise solution, simply go to the installation folder of django-hitcount named "hitcount", go to the migrations folder, and erase everything except the init.py, run python manage.py makemigrations and python manage.py migrate and it's solved, sorry my bad English

Collapse
 
billy_de_cartel profile image
Billy Okeyo

Can't i run it without python 2

Collapse
 
razilator profile image
Vladislav

How to optimize it for the ListView, so that there is no n +1?

Collapse
 
chandan315 profile image
chandan315

How to do order_by with high hit count field? Can you help me?

Collapse
 
chandan315 profile image
chandan315

My view shows 0. How do I solve it? It does not increment by 1

Collapse
 
fabricourt profile image
Fabricourt

Thanks it worked ....

Collapse
 
crow_pigeon_sl profile image
Crow Pigeon

run only in Django 2x

Collapse
 
cavinblake profile image
cavinblake • Edited

hi, will it work with the autoplay videos. Can i work with it..if a video autoplays the view will be counted for that post

Collapse
 
anee_mess profile image
animesh

how do i retrive only the number of views that were made in the current week?