djangopostgresqlgithubhitcounter

Django hitcount order_by("hit_count_generic__hits") gives error on PostgreSQL database


I was using django-hitcont to count the views on my Post model. I am trying to get the most viewed post in my ListView using this query objects.order_by('hit_count_generic__hits') and it is working fine on SQLite but on PostgreSQL, it is giving me this error : django.db.utils.ProgrammingError: operator does not exist: integer = text LINE 1: ...R JOIN "hitcount_hit_count" ON ("posts_post"."id" = "hitcoun....

models.py

class Post(models.Model, HitCountMixin):
    author = models.ForeignKey(User, related_name='authors', on_delete=models.CASCADE)
    title = models.CharField('Post Title', max_length = 150)
    description = models.TextField('Description', max_length=1000, blank = True)
    date_posted = models.DateTimeField('Date posted', default = timezone.now)
    date_modifed = models.DateTimeField('Date last modified', default = timezone.now)
    document = models.FileField('Document of Post', upload_to='documents', \
     validators=[FileExtensionValidator(allowed_extensions = ['pdf', 'docx']), validate_document_size] \
    )
    hit_count_generic = GenericRelation(
    HitCount,
    object_id_field='object_pk',
    related_query_name='hit_count_generic_relation'
   )

views.py

queryset = Post.objects.order_by('hit_count_generic__hits') 

I found this issue on Github related to the problem, but I am still not able to figure out the mentioned workaround.


Solution

  • When comparing different types (in this example integer and text), equals operator throws this exception. To fix that, convert HitCount model pk field to integer and you are good to go. To do that, you need to create and apply migration operation. Django is a really good framework to handle this kind of operations. You just need to check values are not null and are "convertable" to integer. Just change the field type and run two commands below.

    python manage.py makemigrations
    python manage.py migrate
    

    Before updating your model, I highly recommend you to take a backup in case of failure. This is not an easy operation but you can follow the these links to understand what is going on during this the process. migrations dump and restore initial data If you don't care the data on table, just drop table and create a brand new migration file and recreate table.