Django rest框架-过滤多对多字段 [英] Django rest framework - filter many-to-many field

查看:302
本文介绍了Django rest框架-过滤多对多字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的模型:

Suppose I have a model like this one:

class Car(models.Model):
    images = models.ManyToManyField(Image)

class Image(models.Model):
    path = models.CharField()
    type = models.CharField()

我想公开两个API视图:

I want to expose two API views:


  • 汽车列表

  • 汽车详细信息

在列表视图中我只显示图像类型为 thumbnail的缩略图。在详细信息视图中,我想显示类型为 image的图像。

In list view I want to show only images that have type="thumbnail". In details view I want to show images of type="image".

这或多或少是列表的外观:

This is more or less what the list should look like:

[{
    "id": 1,
    "images": [1, 2],
},
{
    "id": 2,
    "images": [3, 4],
}]

和详细信息视图:

{
    "id": 1,
    "images": [5],
}

根据视图显示不同的图像ID。

Note that different image ids are displayed depending on the view.

到目前为止,我的序列化程序如下:

So far my serializer looks like this:

class CarSerializer(serializers.ModelSerializer):
    images = serializers.ManyPrimaryKeyRelatedField()

    class Meta:
        model = Car

列出api视图:

class CarList(generics.ListAPIView):
    model = Car
    serializer_class = CarSerializer

详细信息api视图:

class CarDetails(generics.RetrieveAPIView):
    model = Car
    serializer_class = CarSerializer

这当然给了我列表中的所有图像以及详细信息,并迫使客户进行额外的调用以获取应显示的图像类型

This of course gives me all images in list as well as in details and forces clients to make additional calls to get image type that should be displayed.

有没有通用的方法?我看过django-filter的示例,但似乎只能过滤列出了哪些对象,而没有列出列出的对象中的哪些相关对象。

Is there any generic way to do it? I have seen django-filter examples, but it seems that its only possible to filter which objects are listed, not what related objects in listed objects are listed.

推荐答案

我不知道您是否还在寻找答案,但这也许会对其他人有所帮助。

I don´t know if you are still looking for this answer, but maybe it helps someone else.

首先创建一个这样的过滤器类:

First create a filter class like this:

class CarFilter(django_filters.FilterSet):
    having_image = django_filters.Filter(name="images", lookup_type='in')

    class Meta:
        model = Car

然后将过滤器添加到视图:

Then add the filter to your view:

class CarList(generics.ListAPIView):
    model = Car
    serializer_class = CarSerializer
    filter_class = CarFilter

仅此而已。在查询字符串中添加?having_image = 1,Django过滤器将为您解决问题。

And that´s all. Add "?having_image=1" to your query string and Django filter should do the trick for you.

希望它会有所帮助。.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆