Passing custom serializer request to Django Rest Framework

I am using the Django rest 2.3 platform. I have a class like this

class Quiz(): fields.. # A custom manager for result objects class SavedOnceManager(models.Manager): def filter(self, *args, **kwargs): if not 'saved_once' in kwargs: kwargs['saved_once'] = True return super(SavedOnceManager, self).filter(*args, **kwargs) class Result(): saved_once = models.NullBooleanField(default=False, db_index=True, null=True) quiz = models.ForeignKey(Quiz, related_name='result_set') objects = SavedOnceManager() 

As you can see, I have a user results manager, so Result.objects.filter() will only return results that have save_once set to True

Now my serializers look like this:

 class ResultSerializer(serializers.ModelSerializer): fields... class QuizSerializer(serializers.ModelSerializer): results = ResultSerializer(many=True, required=False, source='result_set') 

Now, if I serialized my quiz, it will only return results for which saved_once set to True . But for a specific use case, I want the serializer to return all objects. I read that I can do this by passing the queryset parameter http://www.django-rest-framework.org/api-guide/relations/ in the section (further section). However, when I try to do this

 results = ResultSerializer(many=True, required=False, source='result_set', queryset= Result.objects.filter( saved_once__in=[True, False])) 

I get TypeError: __init__() got an unexpected keyword argument 'queryset' And, looking at the DRF source code (in my version at least), it does not accept the request argument.

Looking for some guidance on this to see if this is possible ... thanks!

+5
source share
1 answer

In my opinion, a modifying filter like this is not a good practice. It is very difficult to write a solution for you when I cannot use the filter in the Result model without this additional filtering. I would suggest not modifying the filter in this way and instead create a custom dispatcher method that allows you to apply your filter explicitly where necessary, for example /

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

Therefore, you can query for saved_once strings or unfiltered strings as you expected:

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

Here is one way you can use an additional set of queries inside the serializer. However, it seems to me that this most likely will not work for you if the default manager somehow filters out the saved_once objects. Therefore, 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 
+3
source

All Articles