Login

LazyPrimaryKeyRelatedField

Author:
LLyaudet
Posted:
May 13, 2022
Language:
Python
Version:
3.2
Score:
0 (after 0 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 6 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 6 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 1 month ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 2 months ago
  5. Help text hyperlinks by sa2812 1 year, 2 months ago

Comments

Please login first before commenting.