Django hitcount order_by("hit_count_generic__hits") 在 PostgreSQL 数据库上给出错误

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

我使用 django-hitcont 来计算我的 Post 模型的浏览量。我正在尝试使用此查询 objects.order_by('hit_count_generic__hits') 在我的 ListView 中获得查看次数最多的 post 并且它在 SQLite 上工作正常但在 PostgreSQL 上,它给了我这个错误: 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') 

我在 Github 上发现了与该问题相关的 this 问题,但我仍然无法找出上述解决方法。

当比较不同的类型(在这个例子中是整数和文本)时,等于运算符会抛出这个异常。要解决此问题,请将 HitCount 模型 pk 字段转换为整数,然后就可以开始了。为此,您需要创建并应用迁移操作。 Django 是处理此类操作的非常好的框架。您只需要检查值不为空并且 "convertable" 为整数。只需更改字段类型和下面的 运行 两个命令。

python manage.py makemigrations
python manage.py migrate

在更新您的模型之前,我强烈建议您进行备份以防万一。这不是一个简单的操作,但您可以点击这些链接来了解在此过程中发生了什么。 migrations dump and restore initial data 如果您不关心 table 上的数据,只需删除 table 并创建一个全新的迁移文件并重新创建 table.