如何仅在django-filter中传递要过滤的当前用户数据?

时间:2018-02-15 03:46:38

标签: python django django-filter

我正在使用django-filter来过滤我的数据。问题在于过滤器的可用选项,结果基于所有数据,而不仅仅基于当前用户。

models.py

class Product(models.Model):
    title = models.CharField(max_length=264)
    description = models.CharField(max_length=264)
    date_added = models.DateField(auto_now_add=True)
    time_added = models.TimeField(auto_now_add=True)
    user = models.ForeignKey(User, default=1, on_delete=models.CASCADE)

我使用下面的代码仅过滤当前用户的结果:

filters.py

class ProductFilter(django_filters.FilterSet):

    class Meta:
        model = Product

    @property
    def qs(self):
        parent = super(ProductFilter, self).qs
        user = getattr(self.request, "user", None)
        return parent.filter(user=user).order_by("-timestamp")

在我的views.py我试图传递查询集,但没有改变:

class ProductsFilterView(LoginRequiredMixin, FilterView):
    model = Product
    filterset_class = ProductFilter

    def get_queryset(self, **kwargs):
        return self.model.objects.filter(user=self.request.user)

我不确定如何仅对当前用户的数据限制可用的过滤器选项。

因此,总结如何仅将当前用户的数据传递到过滤器中,而不是将整个数据传递到过滤器中,然后根据当前用户的数据进行过滤。

1 个答案:

答案 0 :(得分:2)

<强> filters.py

class ProductFilter(django_filters.FilterSet):

    class Meta:
        title = django_filters.CharFilter(lookup_expr='icontains')
        # And you can also do "lookup_expr='year__gt' and also 'year__lt'" 
        date_added = django_filters.NumberFilter(name='date_added', lookup_expr='year')
        class Meta:
            model = Product
            fields = [] #You can add fields that wants to be displayed

<强> views.py

from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .filters import ProductFilter

# Function Base View
@login_required
def productfilter(request):
     user = request.user
     product_list = Product.objects.filter(user=user)
     product_filter = ProductFilter(request.GET, queryset=product_list)
     return render(request, "template_name.html", {'products': product_list})

#Class Based View
class ProductsFilterView(LoginRequiredMixin, FilterView):
    context_object_name = 'products'
    template_name = 'template_name.html'
    filter_set = ProductFilter
    def get_queryset(self):
        return Product.objects.filter(user=self.request.user)

我希望这很有帮助。