philipn/django-rest-framework-filters

django-rest-framework-filters does not seem to support RelatedFilters with non-default relationships

dwoldenberg1 opened this issue · 0 comments

I have some model code that looks like this:

class Listing(BaseModel):

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    book = models.ForeignKey(Book, to_field="isbn", on_delete=models.CASCADE)

where importantly the listing.book attribute foreign keys to Book objects not through django-id but through isbn as declared in the to_field

In my filter code I then have:

class ListingFilter(FilterSet):
    user = RelatedFilter(UserFilter, field_name='user', queryset=User.objects.all())
    book = RelatedFilter(BookFilter, field_name='book', queryset=Book.objects.all())

    class Meta:
        model = Listing
        fields = {
            'id': '__all__',
            'condition': '__all__'
        }

which utilizes RelatedFilters for both the foreign-keyed objects. I then have this code in for my view:

class ListingViewSet(BaseApiViewSet):
    """
    API Endpoint for Books
    """
    model = Listing
    queryset = model.objects.all().select_related()
    serializer_class = ListingSerializer
    filter_class = ListingFilter

which implements the listing filter. This all seems to work well for most filters and the user end point works just fine.

the call http://127.0.0.1:8000/api/listing?user__username=test accurately returns the listing where the user's username is in fact test. This is what those queries look like according to the debug toolbar.

however, the call http://127.0.0.1:8000/api/listing?book__language=en does not accurately return the listing where the book's language is enflish. It also does not perform the same amount of queries as the prior call. These are the produced queries.

This all leads me to believe there is some disconnect in the backend filtering because the foreign key is not actually the django id. It's also very possible that I am missing something obvious, please let me know if that is the case!