FilterSet nested queryset not working as expected

171 views
Skip to first unread message

mohse...@gmail.com

unread,
Sep 4, 2016, 8:30:00 AM9/4/16
to Django REST framework
Hello
I've created an issue on github, and now posting here to bring discussion to group as @johnraz suggested.

lets see the sim code:
# views.py
class ProductViewSet(ModelViewSet):
    queryset
= Product.objects.all()
    serializer_class
= ProductSerializer

    filter_backends
= (filters.DjangoFilterBackend, filters.OrderingFilter,)
    filter_class
= ProductFilter

   
def get_queryset(self):
        queryset
= super().get_queryset()
       
if self.request.method == 'GET':
            brand_id
= self.request.query_params.get('brand_id', None)
           
if brand_id:
                queryset
= queryset.prefetch_related(Prefetch('resources', queryset=Resource.objects.filter(brand_id=brand_id)))
           
else:
                queryset
= queryset.prefetch_related('resources')
       
return queryset

# filters.py
class ProductFilter(django_filters.FilterSet):
    brand_id
= django_filters.NumberFilter('resources__brand_id')
    min_score
= django_filters.NumberFilter('resources__score', lookup_type='gte', distinct=True)
   
class Meta:
        model
= Product

# models.py
class Resource(models.Model):
    brand
= models.ForeignKey(Brand, related_name='resources')

    score
= models.FloatField(null=True)

   
# Generic relation to Product and like.
    content_type
= models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id
= models.IntegerField()
    content_object
= GenericForeignKey('content_type', 'object_id')

class Product(models.Model):
       
resources = GenericRelation(Resource, related_query_name='product')

when someone query Product endpoint with 'brand_id=100&min_score=45', it means "give me the Products that have a resource with brand_id 100 and scored more that 45". but the result set contains products that have any resource scored more than 45, whether it's brand_id is 100 or not. it seems that ProductFilter class ignores view queryset modifications and creates the queryset from the original model.
any help would be highly appreciated.
Reply all
Reply to author
Forward
0 new messages