Django过滤器:“排序依据”功能

问题描述

我要根据布尔字段“ is_featured”,创建日期和价格对产品进行排序。

我的目标: This is what i want to achieve. Images shows a website that I am taking ideas from.

我目前有一个复选框过滤器(通过django-filter实现),供用户根据品牌和类别进行过滤。您可以在https://ecommercelsm.herokuapp.com/product/

上看到我的“草稿”

我想添加一个sort_by下拉菜单,如所附图像中的菜单,以便用户可以按过滤后的特征,价格或创建日期对产品的订单进行排序,或者不进行过滤。 我不知道该怎么做。有人可以帮忙吗?我觉得我需要在我的ProductFilter中添加更多字段。

models.py


class Product(MPTTModel):

    bool_choices = (
        (True,'Yes'),(False,'No'),)
    parent = TreeForeignKey('self',blank = True,null = True,related_name = 'children',on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    slug = models.SlugField(unique=True,null=False)
    category = TreeManyToManyField(Category,blank = True)
    brand = models.ForeignKey(Brand,on_delete=models.CASCADE,related_name="product") 
    price = models.DecimalField(max_digits=9,decimal_places=2)
    image = models.ImageField(blank = True,upload_to = 'images/')
    is_featured = models.BooleanField(choices=bool_choices)
    created_at = models.DateTimeField(auto_Now_add = True)

    class Meta:
        db_table = 'product'

    class MPTTMeta:
        order_insertion_by = ['name']

class Brand(models.Model):
    name = models.CharField(max_length=30)

class Category(MPTTModel):
    bool_choices = (
        (True,null=False)
    created_at = models.DateTimeField(auto_Now_add = True)

    class Meta:
        db_table = 'categories'
        verbose_name_plural = 'Categories'

filters.py

class ProductFilter(django_filters.FilterSet):

    brand = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckBoxSelectMultiple)
    category = django_filters.ModelMultipleChoiceFilter(widget=forms.CheckBoxSelectMultiple)

    class Meta:
        model = Product 
        fields = ('brand','category') 

    def __init__(self,products= "",category=Category.objects.none(),*args,**kwargs):
        super(ProductFilter,self).__init__(*args,**kwargs)
        self.filters['brand'].queryset = Brand.objects.filter(product__in=products).distinct()  
        self.filters['category'].queryset = category

解决方法

尝试使用Django Filter软件包。对于您的用例,您可以尝试使用其他小部件。

**编辑

SO Post正在解释您要完成的任务。