【问题标题】:How to add a filter in a custom manager?如何在自定义管理器中添加过滤器?
【发布时间】:2013-02-05 14:56:48
【问题描述】:

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

关于如何做的任何线索?

【问题讨论】:

    标签: django django-custom-manager


    【解决方案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')
    

    【讨论】:

    • 嗨艾丹。谢谢回复。以这种方式添加过滤器会给我一个错误:“无法将关键字 'active' 解析到字段中。选择是:...”。看起来我不能使用 WHERE 子句中的额外字段。关于如何以另一种方式做到这一点的任何线索?最好的问候,
    • 好的,我看到了问题(我认为这似乎有点直截了当)。
    猜你喜欢
    • 2018-07-15
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多