When you change dynamicaly the objects manager on your Model class, you may want to have serializers take it into account.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | from django.db.models import Model from django.db.models.manager import Manager from django.db.models.query import QuerySet from rest_framework.serializers import PrimaryKeyRelatedField class LazyPrimaryKeyRelatedField(PrimaryKeyRelatedField): def get_queryset(self): queryset = self.queryset if isinstance(queryset, (QuerySet, Manager)): # Ensure queryset is re-evaluated whenever used. # Note that actually a `Manager` class may also be used as the # queryset argument. This occurs on ModelSerializer fields, # as it allows us to generate a more expressive 'repr' output # for the field. # Eg: 'MyRelationship(queryset=ExampleModel.objects.all())' queryset = queryset.all() elif issubclass(queryset, Model): queryset = queryset.objects.all() else: import inspect raise Exception( f"What is this ? {queryset} {inspect.getmro(queryset)}" f" {inspect.getmro(Model)}" ) return queryset |
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.