通过列表过滤manytomany字段的字段

Filter field of manytomany field by a list

我想使用 Django REST Framework 执行以下操作:

根据 manytomany 字段的字段过滤结果。

查询如下所示: https://endpoint.com/api/artwork/?having_style=Modern,Contemporary

我希望结果包含所有 ArtWork 对象,这些对象包含与名称为“Modern”、“Contemporary”或两者的 Style 对象的关系。

下面的代码不起作用,我不知道为什么。

models.py

class Style(models.Model):
    name = models.CharField(validators=[validate_style], max_length=100, unique=True)

class ArtWork(models.Model):
    styles = models.ManyToManyField(Style, default=None)

filters.py

class ArtWorkFilter(filters_rest.FilterSet):
    having_style = django_filters.Filter(field_name="styles__name", lookup_expr='in')

    class Meta:
        model = ArtWork
        fields = ['having_style']
class StyleSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Style
        fields = ('name',)

class ArtWorkSerializer(serializers.ModelSerializer):

    styles = StyleSerializer(many=True)

    class Meta:
        model = ArtWork
        fields = ('styles'/)

views.py

class ArtWorkViewSet(viewsets.ModelViewSet):

    permission_classes = []

    queryset = ArtWork.objects.all()
    serializer_class = ArtWorkSerializer
    filter_backends = [filters_rest.DjangoFilterBackend,]
    filterset_class= ArtWorkFilter
    pagination_class = CursorSetPagination

提前致谢!

解决方案

我通过将 ArtWorkFilter 更改为

解决了这个问题

filters.py

class ArtWorkFilter(filters_rest.FilterSet):
    having_style = django_filters.Filter(field_name="styles__name", lookup_expr='in')

    class Meta:
        model = ArtWork
        fields = ['having_style']

    def filter_by_style_name(self, queryset, name, value):
        list_styles = value.split(',')
        return queryset.filter(styles__name__in=list_styles)
CartItem.objects.filter(cart=cart, product=product, attribute__in=attribute_list).annotate(num_attr=Count('attribute')).filter(num_attr=len(attribute_list))

尝试在过滤器声明中添加 method 参数。类似于:

class ArtWorkFilter(filters_rest.FilterSet):
    having_style = django_filters.Filter(field_name="styles__name", lookup_expr='in')

    class Meta:
        model = ArtWork
        fields = ['having_style']

    def filter_by_style_name(self, queryset, name, value):
        list_styles = value.split(',')
        return queryset.filter(styles__name__in=list_styles)