Django过滤器按相关字段过滤

Django过滤器按相关字段过滤

本文介绍了Django过滤器按相关字段过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表。

class Writer(models.Model)
    name = model.CharField()
    ...

class Article(models.Model)
    name = model.CharField()
    writer = model.ForeignKey('Writer', related_name="relationship")
    ...

我想构建一些API端点来获取作者列表,但这应该可以按商品ID进行过滤。
我正在使用django-filter。因此:

I wanted to build some API endpoints getting the writer list, but this should be filterable by Article id.I am using django-filter. So:

class WriterViewSet(viewsets.ReadOnlyModelViewSet):
   filter_backend = [filters.djangoFilterBackend],
   filter_class = WriterFilter


class WriteFilter(django_filters.rest_framework.FilterSet):
....

所以我关心的是,如何定义WriteFilter来按文章过滤Writer?

So my concern is, how can I define WriteFilter to filter Writer by the article?

推荐答案

class WriteFilter(django_filters.rest_framework.FilterSet):
    article = django_filters.CharFilter(name='relationship__name', lookup_expr='contains')

    class Meta:
        model = WriterFilter
        fields = ['article']



您的网址将是这样,

/ api / wtiter / list /?article = somearticlename

由于 django-filter 2.0 名称 参数更改为 field_name

因此,过滤器类别为

since django-filter 2.0, the name argument changed to field_name.

Hence the filter class will be,

class WriteFilter(django_filters.rest_framework.FilterSet):
    article = django_filters.CharFilter(field_name='relationship__name', lookup_expr='contains')

    class Meta:
        model = WriterFilter
        fields = ['article']

这篇关于Django过滤器按相关字段过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:23