[Fixed]-Pass a custom queryset to serializer in Django Rest Framework

14πŸ‘

In my opinion, modifying filter like this is not a very good practice. It is very difficult to write a solution for you when I cannot use filter on the Result model without this extra filtering happening. I would suggest not modifying filter in this manner and instead creating a custom manager method which allows you to apply your filter in an obvious way where it is needed, eg/

class SavedOnceManager(models.Manager):                                                                                                                                                                                                
    def saved_once(self):
        return self.get_queryset().filter('saved_once'=True)

Therefore, you can query either the saved_once rows or the unfiltered rows as you would expect:

Results.objects.all()
Results.objects.saved_once().all()

Here is one way which you can use an additional queryset inside a serializer. However, it looks to me that this most likely will not work for you if the default manager is somehow filtering out the saved_once objects. Hence, your problem lies elsewhere.

class QuizSerializer(serializers.ModelSerializer):  
    results = serializers.SerializerMethodField()

    def get_results(self, obj):
        results = Result.objects.filter(id__in=obj.result_set)
        return ResultSerializer(results, many=True).data
πŸ‘€Mark Galloway

Leave a comment