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