【问题标题】:Filter many-to-many field DRF过滤多对多字段 DRF
【发布时间】:2020-12-15 15:14:43
【问题描述】:

我需要使用多对多类别字段过滤文档的 API 响应。这是我的模型:

class Document(models.Model):
    name = models.CharField(max_length = 100, blank = True)
    file = models.FileField(null = True, upload_to='documents/', validators=[FileExtensionValidator(allowed_extensions=['pdf'])])
    date_created = models.DateTimeField(auto_now_add = True, null = True)
    category = models.ManyToManyField(Category)
    company = models.ForeignKey(Company, null = True, on_delete = models.SET_NULL)
    author = models.ForeignKey(Employee, null = True, on_delete = models.SET_NULL)

这个模型的序列化器是:

class DocumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Document
        fields = "__all__"

我正在尝试用这个过滤它:

class DocumentFilter(filters.FilterSet):
    # having_category = filters.Filter(name = 'category', lookup_type = 'in')
    class Meta:
        model = Document
        fields = {
            'company': ['exact'],
            'author': ['exact'],
            # 'category': ['in']
        }

我尝试使用this 解决方案,正如您在代码中看到的那样,但没有成功。 与公司和作者一起过滤正在工作,我只遇到了类别问题。

我应该如何创建过滤器?

【问题讨论】:

    标签: django filter django-rest-framework


    【解决方案1】:

    你可以参考这里https://django-filter.readthedocs.io/en/stable/ref/filters.html

    import django_filters
    
    class DocumentFilter(django_filters.FilterSet):
        company = django_filters.CharFilter(lookup_expr="exact", field_name='company__name')
        author = django_filters.CharFilter(lookup_expr="exact", field_name='author__name')
        category = django_filters.CharFilter(method='filter_category')
    
        class Meta:
            model = Document
            fields = ['company', 'author', 'category']
    
        def filter_category(self, queryset, name, value):
            categories = value.split(',')
            return queryset.filter(category__name__in=categories)
    

    【讨论】:

    • 乐于助人
    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 2018-06-07
    • 2015-07-18
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    相关资源
    最近更新 更多