简体   繁体   English

Django结合Q对象和order_by

[英]Django combine Q object with order_by

I'm trying to abstract all the filtering logic of a form SearchForm(forms.Form) in a function called get_filters . 我正在尝试在名为get_filters的函数中抽象形式SearchForm(forms.Form)所有过滤逻辑。

get_filters returns a Q object which is then used by the view to filter the actual queryset. get_filters返回一个Q对象,该对象随后被视图用来过滤实际的查询集。 As such, get_filters doesn't and mustn't know anything about the queryset: its job is just that of returning a filter which can be passed to .filter() 这样, get_filters 也不知道有关查询集的任何信息:它的工作只是返回可以传递给.filter()的过滤器。

views.py: views.py:

def my_view(request):
    form = SearchForm(request.GET)

    if form.is_valid():
        filters = form.get_filters()
        Model.objects.filter(filters)

forms.py: forms.py:

class SearchForm(forms.Form):
    """
    Fields...
    """
    def get_filters(self):
        """
        filtering logic
        """
        return Q(some_filters)

This works fine. 这很好。 However, I now need an "order by" field. 但是,我现在需要一个“ order by”字段。

Can I do that with Q objects in the get_filters function? 我可以对get_filters函数中的Q对象执行此get_filters吗? Or I have no way other than breaking this programming pattern and access form.cleaned_data in the view? 或者我除了打破这种编程模式并在视图中访问form.cleaned_data

Instead of get_filter doing the order_by, can you have the view do it? 您可以使用视图代替get_filter来执行order_by吗?

from my_app.models import Project
filters = get_filters(form)
ps = Project.objects.order_by('name').filter(filters)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM