django-datatables-view加载过滤模型

时间:2015-04-24 18:01:58

标签: python django datatables django-datatable

这里我们有使django-datatables-view显示的基本代码

from django_datatables_view.base_datatable_view import BaseDatatableView

class OrderListJson(BaseDatatableView):
    # The model we're going to show
    model = MyModel

    # define the columns that will be returned
    columns = ['number', 'user', 'state', 'created', 'modified']

    # define column names that will be used in sorting
    # order is important and should be same as order of columns
    # displayed by datatables. For non sortable columns use empty
    # value like ''
    order_columns = ['number', 'user', 'state', '', '']

    # set max limit of records returned, this is used to protect our site if someone tries to attack our site
    # and make it return huge amount of data
    max_display_length = 500

    def render_column(self, row, column):
        # We want to render user as a custom column
        if column == 'user':
            return '{0} {1}'.format(row.customer_firstname, row.customer_lastname)
        else:
            return super(OrderListJson, self).render_column(row, column)

    def filter_queryset(self, qs):
        # use parameters passed in GET request to filter queryset

        # simple example:
        search = self.request.GET.get(u'search[value]', None)
        if search:
            qs = qs.filter(name__istartswith=search)

        # more advanced example using extra parameters
        filter_customer = self.request.GET.get(u'customer', None)

        if filter_customer:
            customer_parts = filter_customer.split(' ')
            qs_params = None
            for part in customer_parts:
                q = Q(customer_firstname__istartswith=part)|Q(customer_lastname__istartswith=part)
                qs_params = qs_params | q if qs_params else q
            qs = qs.filter(qs_params)
        return qs

此代码工作正常,但是,如何让它不显示整个模型,而只是从模型中过滤内容?我已经尝试将其设置为model = MyModel.objects.filter(name="example"),但这会返回错误。

2 个答案:

答案 0 :(得分:1)

def get_initial_queryset(self):
     return MyModel.objects.filter(name="example")

在您的班级OrderListJson

中添加此内容

答案 1 :(得分:0)

您可以使用get_initial_queryset方法返回用于填充数据表的查询集。