models.py 12 KB

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