1

我坚持向 Django 中的自定义管理器添加过滤器。这是我当前正在工作的自定义管理器:

class VoteAwareManager(models.Manager):

    def _get_score_annotation(self):
        model_type = ContentType.objects.get_for_model(self.model)
        table_name = self.model._meta.db_table
        return self.extra(select={
            'active': 'select active from %s mh where mh.main_id = %s.id and mh.active = true and mh.date_begin = (select max(date_begin) from euvoudebicicletaengine_mainhistoric where main_id = mh.main_id) and mh.date_end >= now()' % (MainHistoric._meta.db_table, table_name),
            'row_num': '(row_number() over(order by (SELECT COALESCE(SUM(vote / ((extract(epoch from now() - time_stamp )/3600)+2)^1.5),0) FROM %s WHERE content_type_id=%d AND object_id=%s.id) DESC))' % (Vote._meta.db_table, int(model_type.id), table_name), # To know the position(#number) on the front page
            'score': 'SELECT COALESCE(SUM(vote / ((extract(epoch from now() - time_stamp )/3600)+2)^1.5),0) FROM %s WHERE content_type_id=%d AND object_id=%s.id' % (Vote._meta.db_table, int(model_type.id), table_name)
                }
        )

    def most_loved(self,):
        return self._get_score_annotation().order_by('-score')

    def most_hated(self):
        return self._get_score_annotation().order_by('score')

我需要在主 sql 表达式中添加一个过滤器most_loved,这将是等效于 SQL的 SQL。most_hatedactive=Truewhere active=true

关于如何做的任何线索?

4

1 回答 1

1

我认为您可能需要编写一个 SQL 视图(以替换您的函数)并为该视图extra()创建一个新的非托管模型active(包括作为模型中的一个字段)。

正如在这个问题中一样。或者这个(可能已经过时)一个。

然后使用您的视图_get_score_annotation并将过滤器添加到您从该函数获得的查询集中。

def _get_score_annotation(self):
    return ContentTypeView.objects.filter(# any filtering you need)

def most_loved(self,):
    return self._get_score_annotation().filter(active=True).order_by('-score')
于 2013-02-20T14:50:15.187 回答