1 | #!/usr/bin/env python
|
---|
2 |
|
---|
3 | import sys
|
---|
4 | import textwrap
|
---|
5 |
|
---|
6 | from django.apps import apps
|
---|
7 | from django.apps.config import AppConfig
|
---|
8 | from django.conf import settings
|
---|
9 | from django.db import models
|
---|
10 | from django.http import HttpResponse
|
---|
11 |
|
---|
12 | APP_LABEL = "femto"
|
---|
13 |
|
---|
14 | settings.configure(DEBUG=True, SECRET_KEY="topsecret", ROOT_URLCONF=__name__)
|
---|
15 | app_config = AppConfig(APP_LABEL, sys.modules["__main__"])
|
---|
16 | apps.populate([app_config])
|
---|
17 |
|
---|
18 |
|
---|
19 | class Animal(models.Model):
|
---|
20 | class Meta:
|
---|
21 | app_label = APP_LABEL
|
---|
22 |
|
---|
23 |
|
---|
24 | class Mammal(Animal):
|
---|
25 | class Meta:
|
---|
26 | app_label = APP_LABEL
|
---|
27 |
|
---|
28 |
|
---|
29 | class Cat(Mammal):
|
---|
30 | class Meta:
|
---|
31 | app_label = APP_LABEL
|
---|
32 |
|
---|
33 |
|
---|
34 | # Try getting Animal by an erroneous non-integer pk; result should be ValueError
|
---|
35 | try:
|
---|
36 | Animal.objects.get(pk="hello")
|
---|
37 | except ValueError as e:
|
---|
38 | print(str(e))
|
---|
39 | print("Animal raised ValueError")
|
---|
40 |
|
---|
41 | # Same thing with Mammal
|
---|
42 | try:
|
---|
43 | Mammal.objects.get(pk="hello")
|
---|
44 | except ValueError as e:
|
---|
45 | print(str(e))
|
---|
46 | print("Mammal raised ValueError")
|
---|
47 |
|
---|
48 | # But Cat, instead of ValueError, raises something else
|
---|
49 | try:
|
---|
50 | Cat.objects.get(pk="hello")
|
---|
51 | except ValueError:
|
---|
52 | print("Cat raised ValueError")
|
---|
53 | except Exception as e:
|
---|
54 | print()
|
---|
55 | print(str(e))
|
---|
56 | print(
|
---|
57 | textwrap.dedent(
|
---|
58 | """\
|
---|
59 | Oops! Cat raised something else than ValueError. In this example it's
|
---|
60 | probably ImproperlyConfigured because DATABASES is missing, but if this had
|
---|
61 | been properly configured, it would have been DataError, because it would
|
---|
62 | have created and run SQL that contains 'hello' as an integer. In contrast,
|
---|
63 | Animal and Mammal caught the error earlier. The most important thing is that
|
---|
64 | in all three cases there should have been the same exception.
|
---|
65 | """
|
---|
66 | )
|
---|
67 | )
|
---|