Pass a custom queryset to serializer in Django Rest Framework

后端 未结 1 1392
谎友^
谎友^ 2021-02-19 07:25

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.Man         


        
相关标签:
1条回答
  • 2021-02-19 07:54

    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
    
    0 讨论(0)
提交回复
热议问题