models.py 12 KB

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