如何在自定义管理器中添加过滤器?

时间:2013-02-20 14:48:54

标签: django django-custom-manager

我一直在为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')

我需要在most_lovedmost_hatedactive=True添加一个过滤器,它将是主sql表达式中与where active=true等效的SQL。

关于如何做的任何线索?

1 个答案:

答案 0 :(得分:1)

我认为您可能需要编写SQL视图(以替换extra()函数)并为视图创建新的unmanaged model(包括active作为模型中的字段)

this问题一样。或this(可能已过期)。

然后使用_get_score_annotation中的视图,并在您从该功能获得的查询集中添加filter

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')