#!/usr/bin/env python

import sys
import textwrap

from django.apps import apps
from django.apps.config import AppConfig
from django.conf import settings
from django.db import models
from django.http import HttpResponse

APP_LABEL = "femto"

settings.configure(DEBUG=True, SECRET_KEY="topsecret", ROOT_URLCONF=__name__)
app_config = AppConfig(APP_LABEL, sys.modules["__main__"])
apps.populate([app_config])


class Animal(models.Model):
    class Meta:
        app_label = APP_LABEL


class Mammal(Animal):
    class Meta:
        app_label = APP_LABEL


class Cat(Mammal):
    class Meta:
        app_label = APP_LABEL


# Try getting Animal by an erroneous non-integer pk; result should be ValueError
try:
    Animal.objects.get(pk="hello")
except ValueError as e:
    print(str(e))
    print("Animal raised ValueError")

# Same thing with Mammal
try:
    Mammal.objects.get(pk="hello")
except ValueError as e:
    print(str(e))
    print("Mammal raised ValueError")

# But Cat, instead of ValueError, raises something else
try:
    Cat.objects.get(pk="hello")
except ValueError:
    print("Cat raised ValueError")
except Exception as e:
    print()
    print(str(e))
    print(
        textwrap.dedent(
            """\
            Oops! Cat raised something else than ValueError. In this example it's
            probably ImproperlyConfigured because DATABASES is missing, but if this had
            been properly configured, it would have been DataError, because it would
            have created and run SQL that contains 'hello' as an integer. In contrast,
            Animal and Mammal caught the error earlier. The most important thing is that
            in all three cases there should have been the same exception.
            """
        )
    )
