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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 2 months, 4 weeks ago
  2. Python Django CRUD Example Tutorial by tuts_station 3 months, 2 weeks ago
  3. Browser-native date input field by kytta 4 months, 4 weeks ago
  4. Generate and render HTML Table by LLyaudet 5 months, 1 week ago
  5. My firs Snippets by GutemaG 5 months, 1 week ago

Comments

Please login first before commenting.