限制Django-Filter中字段的querset

时间:2014-02-20 21:22:22

标签: python django django-filter

我有一个django-filter FilterSet,它接受​​用户保存链接的查询集。标签是ManyToManyField,我想将该选择范围缩小到同一用户创建(拥有)的标签。完全不知所措 - 文档并不那么广泛。

class LinkFilter(django_filters.FilterSet):

    class Meta:
        model = Link
        fields = ['title', 'domain', 'tags', 'date', 'modified']

https://github.com/alex/django-filter/

3 个答案:

答案 0 :(得分:1)

之前我没有使用过django-filter,但是看一下你应该可以做下面的文档。您需要在LinkFilter的构造函数中为关键字参数user传递要过滤的用户。否则,它将继续显示所有用户的所有标签。我还猜测Link类上的User ForeignKey属性名为created_by

class LinkFilter(django_filters.FilterSet):
    class Meta:
        model = Link
        fields = ['title', 'domain', 'tags', 'date', 'modified']

    def __init__(self, data=None, queryset=None, prefix=None, strict=None, user=None):
        super(LinkFilter, self).__init__(data=data, queryset=queryset, prefix=prefix, strict=strict))
        if user:
            self.filters['tags'].filter(created_by=user)

答案 1 :(得分:1)

以下是我为一个非常类似的情况(试图适应你的情况)做的:

class LinkFilter(django_filters.FilterSet):

    def __init__(self, *args, **kwargs):
        current_user = kwargs['current_user']
        del kwargs['current_user']
        super(LinkFilter, self).__init__(*args, **kwargs)
        self.filters['customer'].extra.update(
            {'queryset': models.Tags.objects.get_my_tags(current_user)})

    class Meta:
        model = Link
        fields = ['title', 'domain', 'tags', 'date', 'modified']
在您看来

def home(request):
    f = LinkFilter(request.GET, queryset=models.Links.objects.get_my_links(request.user), current_user=request.user)
    return render_to_response('public/links.html', {'filter': f})

我的get_my_tags文件中定义了get_my_linksmanagers.py

答案 2 :(得分:0)

class ProductFilter(FilterSet):
    def __init__(self,data=None, queryset=None, prefix=None, strict=None, **kwargs):
        self.kwargs = kwargs
        super(ProductFilter, self).__init__(data, queryset, prefix, strict)

    @property
    def form(self):
        form = super(ProductFilter, self).form

        for key, queryset in self.kwargs.iteritems():
            form.fields[key].queryset = queryset

        return form

    class Meta:
        model = Product
        fields = ['name', 'tags']

class ViewFilter(TemplateView):
    template_name = 'frontend/view_filter.html'
    def get_context_data(self, **kwargs):
        context = super(ViewFilter, self).get_context_data(**kwargs)

        context['filter'] = ProductFilter(self.request.GET,
                                          queryset=Product.objects.filter(tags__user_id=2),
                                          tags=Tag.objects.filter(user_id=2))

        return context