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
- New Snippet! by Antoliny0919 4 days, 14 hours ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months, 3 weeks ago
- get_object_or_none by azwdevops 6 months, 2 weeks ago
- Mask sensitive data from logger by agusmakmun 8 months, 1 week ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 10 months ago
Comments
Please login first before commenting.