Skip to content Skip to sidebar Skip to footer

Pass A Custom Queryset To Serializer In Django Rest Framework

I am using Django rest framework 2.3 I have a class like this class Quiz(): fields.. # A custom manager for result objects class SavedOnceManager(models.Manager):

Solution 1:

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/

classSavedOnceManager(models.Manager):                                                                                                                                                                                                
    defsaved_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.

classQuizSerializer(serializers.ModelSerializer):  
    results = serializers.SerializerMethodField()

    def get_results(self, obj):
        results = Result.objects.filter(id__in=obj.result_set)
        returnResultSerializer(results, many=True).data

Post a Comment for "Pass A Custom Queryset To Serializer In Django Rest Framework"