models.py 12 KB

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