models.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. import json
  2. import tempfile
  3. import uuid
  4. from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.core.files.storage import FileSystemStorage
  7. from django.core.serializers.json import DjangoJSONEncoder
  8. from django.db import models
  9. from django.db.models.fields.files import ImageFieldFile
  10. from django.utils.translation import gettext_lazy as _
  11. try:
  12. from PIL import Image
  13. except ImportError:
  14. Image = None
  15. class Foo(models.Model):
  16. a = models.CharField(max_length=10)
  17. d = models.DecimalField(max_digits=5, decimal_places=3)
  18. def get_foo():
  19. return Foo.objects.get(id=1).pk
  20. class Bar(models.Model):
  21. b = models.CharField(max_length=10)
  22. a = models.ForeignKey(Foo, models.CASCADE, default=get_foo, related_name="bars")
  23. class Whiz(models.Model):
  24. CHOICES = (
  25. (
  26. "Group 1",
  27. (
  28. (1, "First"),
  29. (2, "Second"),
  30. ),
  31. ),
  32. (
  33. "Group 2",
  34. (
  35. (3, "Third"),
  36. (4, "Fourth"),
  37. ),
  38. ),
  39. (0, "Other"),
  40. (5, _("translated")),
  41. )
  42. c = models.IntegerField(choices=CHOICES, null=True)
  43. class WhizDelayed(models.Model):
  44. c = models.IntegerField(choices=(), null=True)
  45. # Contrived way of adding choices later.
  46. WhizDelayed._meta.get_field("c").choices = Whiz.CHOICES
  47. class WhizIter(models.Model):
  48. c = models.IntegerField(choices=iter(Whiz.CHOICES), null=True)
  49. class WhizIterEmpty(models.Model):
  50. c = models.CharField(choices=iter(()), blank=True, max_length=1)
  51. class Choiceful(models.Model):
  52. class Suit(models.IntegerChoices):
  53. DIAMOND = 1, "Diamond"
  54. SPADE = 2, "Spade"
  55. HEART = 3, "Heart"
  56. CLUB = 4, "Club"
  57. no_choices = models.IntegerField(null=True)
  58. empty_choices = models.IntegerField(choices=(), null=True)
  59. with_choices = models.IntegerField(choices=[(1, "A")], null=True)
  60. empty_choices_bool = models.BooleanField(choices=())
  61. empty_choices_text = models.TextField(choices=())
  62. choices_from_enum = models.IntegerField(choices=Suit)
  63. class BigD(models.Model):
  64. d = models.DecimalField(max_digits=32, decimal_places=30)
  65. class FloatModel(models.Model):
  66. size = models.FloatField()
  67. class BigS(models.Model):
  68. s = models.SlugField(max_length=255)
  69. class UnicodeSlugField(models.Model):
  70. s = models.SlugField(max_length=255, allow_unicode=True)
  71. class AutoModel(models.Model):
  72. value = models.AutoField(primary_key=True)
  73. class BigAutoModel(models.Model):
  74. value = models.BigAutoField(primary_key=True)
  75. class SmallAutoModel(models.Model):
  76. value = models.SmallAutoField(primary_key=True)
  77. class SmallIntegerModel(models.Model):
  78. value = models.SmallIntegerField()
  79. class IntegerModel(models.Model):
  80. value = models.IntegerField()
  81. class BigIntegerModel(models.Model):
  82. value = models.BigIntegerField()
  83. null_value = models.BigIntegerField(null=True, blank=True)
  84. class PositiveBigIntegerModel(models.Model):
  85. value = models.PositiveBigIntegerField()
  86. class PositiveSmallIntegerModel(models.Model):
  87. value = models.PositiveSmallIntegerField()
  88. class PositiveIntegerModel(models.Model):
  89. value = models.PositiveIntegerField()
  90. class Post(models.Model):
  91. title = models.CharField(max_length=100)
  92. body = models.TextField()
  93. class NullBooleanModel(models.Model):
  94. nbfield = models.BooleanField(null=True, blank=True)
  95. class BooleanModel(models.Model):
  96. bfield = models.BooleanField()
  97. class DateTimeModel(models.Model):
  98. d = models.DateField()
  99. dt = models.DateTimeField()
  100. t = models.TimeField()
  101. class DurationModel(models.Model):
  102. field = models.DurationField()
  103. class NullDurationModel(models.Model):
  104. field = models.DurationField(null=True)
  105. class PrimaryKeyCharModel(models.Model):
  106. string = models.CharField(max_length=10, primary_key=True)
  107. class FksToBooleans(models.Model):
  108. """Model with FKs to models with {Null,}BooleanField's, #15040"""
  109. bf = models.ForeignKey(BooleanModel, models.CASCADE)
  110. nbf = models.ForeignKey(NullBooleanModel, models.CASCADE)
  111. class FkToChar(models.Model):
  112. """Model with FK to a model with a CharField primary key, #19299"""
  113. out = models.ForeignKey(PrimaryKeyCharModel, models.CASCADE)
  114. class RenamedField(models.Model):
  115. modelname = models.IntegerField(name="fieldname", choices=((1, "One"),))
  116. class VerboseNameField(models.Model):
  117. id = models.AutoField("verbose pk", primary_key=True)
  118. field1 = models.BigIntegerField("verbose field1")
  119. field2 = models.BooleanField("verbose field2", default=False)
  120. field3 = models.CharField("verbose field3", max_length=10)
  121. field4 = models.DateField("verbose field4")
  122. field5 = models.DateTimeField("verbose field5")
  123. field6 = models.DecimalField("verbose field6", max_digits=6, decimal_places=1)
  124. field7 = models.EmailField("verbose field7")
  125. field8 = models.FileField("verbose field8", upload_to="unused")
  126. field9 = models.FilePathField("verbose field9")
  127. field10 = models.FloatField("verbose field10")
  128. # Don't want to depend on Pillow in this test
  129. # field_image = models.ImageField("verbose field")
  130. field11 = models.IntegerField("verbose field11")
  131. field12 = models.GenericIPAddressField("verbose field12", protocol="ipv4")
  132. field13 = models.PositiveIntegerField("verbose field13")
  133. field14 = models.PositiveSmallIntegerField("verbose field14")
  134. field15 = models.SlugField("verbose field15")
  135. field16 = models.SmallIntegerField("verbose field16")
  136. field17 = models.TextField("verbose field17")
  137. field18 = models.TimeField("verbose field18")
  138. field19 = models.URLField("verbose field19")
  139. field20 = models.UUIDField("verbose field20")
  140. field21 = models.DurationField("verbose field21")
  141. class GenericIPAddress(models.Model):
  142. ip = models.GenericIPAddressField(null=True, protocol="ipv4")
  143. ###############################################################################
  144. # These models aren't used in any test, just here to ensure they validate
  145. # successfully.
  146. # See ticket #16570.
  147. class DecimalLessThanOne(models.Model):
  148. d = models.DecimalField(max_digits=3, decimal_places=3)
  149. # See ticket #18389.
  150. class FieldClassAttributeModel(models.Model):
  151. field_class = models.CharField
  152. ###############################################################################
  153. class DataModel(models.Model):
  154. short_data = models.BinaryField(max_length=10, default=b"\x08")
  155. data = models.BinaryField()
  156. ###############################################################################
  157. # FileField
  158. class Document(models.Model):
  159. myfile = models.FileField(upload_to="unused", unique=True)
  160. ###############################################################################
  161. # ImageField
  162. # If Pillow available, do these tests.
  163. if Image:
  164. class TestImageFieldFile(ImageFieldFile):
  165. """
  166. Custom Field File class that records whether or not the underlying file
  167. was opened.
  168. """
  169. def __init__(self, *args, **kwargs):
  170. self.was_opened = False
  171. super().__init__(*args, **kwargs)
  172. def open(self):
  173. self.was_opened = True
  174. super().open()
  175. class TestImageField(models.ImageField):
  176. attr_class = TestImageFieldFile
  177. # Set up a temp directory for file storage.
  178. temp_storage_dir = tempfile.mkdtemp()
  179. temp_storage = FileSystemStorage(temp_storage_dir)
  180. class Person(models.Model):
  181. """
  182. Model that defines an ImageField with no dimension fields.
  183. """
  184. name = models.CharField(max_length=50)
  185. mugshot = TestImageField(storage=temp_storage, upload_to="tests")
  186. class AbstractPersonWithHeight(models.Model):
  187. """
  188. Abstract model that defines an ImageField with only one dimension field
  189. to make sure the dimension update is correctly run on concrete subclass
  190. instance post-initialization.
  191. """
  192. mugshot = TestImageField(
  193. storage=temp_storage, upload_to="tests", height_field="mugshot_height"
  194. )
  195. mugshot_height = models.PositiveSmallIntegerField()
  196. class Meta:
  197. abstract = True
  198. class PersonWithHeight(AbstractPersonWithHeight):
  199. """
  200. Concrete model that subclass an abstract one with only on dimension
  201. field.
  202. """
  203. name = models.CharField(max_length=50)
  204. class PersonWithHeightAndWidth(models.Model):
  205. """
  206. Model that defines height and width fields after the ImageField.
  207. """
  208. name = models.CharField(max_length=50)
  209. mugshot = TestImageField(
  210. storage=temp_storage,
  211. upload_to="tests",
  212. height_field="mugshot_height",
  213. width_field="mugshot_width",
  214. )
  215. mugshot_height = models.PositiveSmallIntegerField()
  216. mugshot_width = models.PositiveSmallIntegerField()
  217. class PersonDimensionsFirst(models.Model):
  218. """
  219. Model that defines height and width fields before the ImageField.
  220. """
  221. name = models.CharField(max_length=50)
  222. mugshot_height = models.PositiveSmallIntegerField()
  223. mugshot_width = models.PositiveSmallIntegerField()
  224. mugshot = TestImageField(
  225. storage=temp_storage,
  226. upload_to="tests",
  227. height_field="mugshot_height",
  228. width_field="mugshot_width",
  229. )
  230. class PersonTwoImages(models.Model):
  231. """
  232. Model that:
  233. * Defines two ImageFields
  234. * Defines the height/width fields before the ImageFields
  235. * Has a nullable ImageField
  236. """
  237. name = models.CharField(max_length=50)
  238. mugshot_height = models.PositiveSmallIntegerField()
  239. mugshot_width = models.PositiveSmallIntegerField()
  240. mugshot = TestImageField(
  241. storage=temp_storage,
  242. upload_to="tests",
  243. height_field="mugshot_height",
  244. width_field="mugshot_width",
  245. )
  246. headshot_height = models.PositiveSmallIntegerField(blank=True, null=True)
  247. headshot_width = models.PositiveSmallIntegerField(blank=True, null=True)
  248. headshot = TestImageField(
  249. blank=True,
  250. null=True,
  251. storage=temp_storage,
  252. upload_to="tests",
  253. height_field="headshot_height",
  254. width_field="headshot_width",
  255. )
  256. class CustomJSONDecoder(json.JSONDecoder):
  257. def __init__(self, object_hook=None, *args, **kwargs):
  258. return super().__init__(object_hook=self.as_uuid, *args, **kwargs)
  259. def as_uuid(self, dct):
  260. if "uuid" in dct:
  261. dct["uuid"] = uuid.UUID(dct["uuid"])
  262. return dct
  263. class JSONModel(models.Model):
  264. value = models.JSONField()
  265. class Meta:
  266. required_db_features = {"supports_json_field"}
  267. class NullableJSONModel(models.Model):
  268. value = models.JSONField(blank=True, null=True)
  269. value_custom = models.JSONField(
  270. encoder=DjangoJSONEncoder,
  271. decoder=CustomJSONDecoder,
  272. null=True,
  273. )
  274. class Meta:
  275. required_db_features = {"supports_json_field"}
  276. class RelatedJSONModel(models.Model):
  277. value = models.JSONField()
  278. json_model = models.ForeignKey(NullableJSONModel, models.CASCADE)
  279. class Meta:
  280. required_db_features = {"supports_json_field"}
  281. class AllFieldsModel(models.Model):
  282. big_integer = models.BigIntegerField()
  283. binary = models.BinaryField()
  284. boolean = models.BooleanField(default=False)
  285. char = models.CharField(max_length=10)
  286. date = models.DateField()
  287. datetime = models.DateTimeField()
  288. decimal = models.DecimalField(decimal_places=2, max_digits=2)
  289. duration = models.DurationField()
  290. email = models.EmailField()
  291. file_path = models.FilePathField()
  292. floatf = models.FloatField()
  293. integer = models.IntegerField()
  294. generic_ip = models.GenericIPAddressField()
  295. positive_integer = models.PositiveIntegerField()
  296. positive_small_integer = models.PositiveSmallIntegerField()
  297. slug = models.SlugField()
  298. small_integer = models.SmallIntegerField()
  299. text = models.TextField()
  300. time = models.TimeField()
  301. url = models.URLField()
  302. uuid = models.UUIDField()
  303. fo = models.ForeignObject(
  304. "self",
  305. on_delete=models.CASCADE,
  306. from_fields=["positive_integer"],
  307. to_fields=["id"],
  308. related_name="reverse",
  309. )
  310. fk = models.ForeignKey("self", models.CASCADE, related_name="reverse2")
  311. m2m = models.ManyToManyField("self")
  312. oto = models.OneToOneField("self", models.CASCADE)
  313. object_id = models.PositiveIntegerField()
  314. content_type = models.ForeignKey(ContentType, models.CASCADE)
  315. gfk = GenericForeignKey()
  316. gr = GenericRelation(DataModel)
  317. class ManyToMany(models.Model):
  318. m2m = models.ManyToManyField("self")
  319. ###############################################################################
  320. class UUIDModel(models.Model):
  321. field = models.UUIDField()
  322. class NullableUUIDModel(models.Model):
  323. field = models.UUIDField(blank=True, null=True)
  324. class PrimaryKeyUUIDModel(models.Model):
  325. id = models.UUIDField(primary_key=True, default=uuid.uuid4)
  326. class RelatedToUUIDModel(models.Model):
  327. uuid_fk = models.ForeignKey("PrimaryKeyUUIDModel", models.CASCADE)
  328. class UUIDChild(PrimaryKeyUUIDModel):
  329. pass
  330. class UUIDGrandchild(UUIDChild):
  331. pass