Skip to content

QueryFilters - Nested Relation Filters  #865

@mtnntn

Description

@mtnntn

Hi everyone,

according to the documentation seems that should be possible to filter resources based on their relationships using a query string like ?filter[inventory.item.partNum]=123456.

I have the following models:

class Genre(models.Model):
    name = models.CharField(unique=True, max_length=255)

class Film(models.Model):
    title = models.CharField(unique=True, max_length=255)
    genres = models.ManyToManyField('films.Genre')

I have the following serializers:

class GenreSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Genre
        fields = ['name']

class FilmSerializer(serializers.HyperlinkedModelSerializer):
    included_serializers = { 'genres': GenreSerializer }
    genres = ResourceRelatedField(queryset=Genre.objects, many=True)
    class Meta:
        model = Film
        fields = ["title", "genres"]

And I have this view:

class FilmsViewSet(views.ReadOnlyModelViewSet):
    queryset = Film.objects.prefetch_related('genres')
    serializer_class = FilmSerializer
    filterset_fields = {
        'title': ('icontains', 'iexact', 'contains',),
        'genres': ("exact",),
    }

Unfortunately I had some issues trying to:

  • filter out films based on their genres.name (or properties in general, i.e: filter[genres.name.icontains]=abc )
  • filter out films based on their genres.id (specifying other lookup functions, i.e: filter[genres.id.in]=1,2)
    I know that for this specific case is possible to use this form fitler[genres]=1&filter[genres]=2 but it would be nice to customize this behavior to avoid long urls (I think it is slightly counterintuitive too since the conditions should represent AND clauses not OR, but this is only a personal idea).

It would be nice to add more information on the docs.
Thanks!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions