models.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. from django.db import models
  2. from django.contrib.auth.models import User
  3. from django.conf import settings
  4. import os
  5. class Animal(models.Model):
  6. name = models.CharField(max_length=150)
  7. latin_name = models.CharField(max_length=150)
  8. count = models.IntegerField()
  9. weight = models.FloatField()
  10. # use a non-default name for the default manager
  11. specimens = models.Manager()
  12. def __unicode__(self):
  13. return self.name
  14. def animal_pre_save_check(signal, sender, instance, **kwargs):
  15. "A signal that is used to check the type of data loaded from fixtures"
  16. print 'Count = %s (%s)' % (instance.count, type(instance.count))
  17. print 'Weight = %s (%s)' % (instance.weight, type(instance.weight))
  18. class Plant(models.Model):
  19. name = models.CharField(max_length=150)
  20. class Meta:
  21. # For testing when upper case letter in app name; regression for #4057
  22. db_table = "Fixtures_regress_plant"
  23. class Stuff(models.Model):
  24. name = models.CharField(max_length=20, null=True)
  25. owner = models.ForeignKey(User, null=True)
  26. def __unicode__(self):
  27. # Oracle doesn't distinguish between None and the empty string.
  28. # This hack makes the test case pass using Oracle.
  29. name = self.name
  30. if settings.DATABASE_ENGINE == 'oracle' and name == u'':
  31. name = None
  32. return unicode(name) + u' is owned by ' + unicode(self.owner)
  33. class Absolute(models.Model):
  34. name = models.CharField(max_length=40)
  35. load_count = 0
  36. def __init__(self, *args, **kwargs):
  37. super(Absolute, self).__init__(*args, **kwargs)
  38. Absolute.load_count += 1
  39. class Parent(models.Model):
  40. name = models.CharField(max_length=10)
  41. class Child(Parent):
  42. data = models.CharField(max_length=10)
  43. # Models to regression test #7572
  44. class Channel(models.Model):
  45. name = models.CharField(max_length=255)
  46. class Article(models.Model):
  47. title = models.CharField(max_length=255)
  48. channels = models.ManyToManyField(Channel)
  49. class Meta:
  50. ordering = ('id',)
  51. # Models to regression test #11428
  52. class Widget(models.Model):
  53. name = models.CharField(max_length=255)
  54. class Meta:
  55. ordering = ('name',)
  56. def __unicode__(self):
  57. return self.name
  58. class WidgetProxy(Widget):
  59. class Meta:
  60. proxy = True
  61. # Check for forward references in FKs and M2Ms with natural keys
  62. class TestManager(models.Manager):
  63. def get_by_natural_key(self, key):
  64. return self.get(name=key)
  65. class Store(models.Model):
  66. objects = TestManager()
  67. name = models.CharField(max_length=255)
  68. class Meta:
  69. ordering = ('name',)
  70. def __unicode__(self):
  71. return self.name
  72. def natural_key(self):
  73. return (self.name,)
  74. class Person(models.Model):
  75. objects = TestManager()
  76. name = models.CharField(max_length=255)
  77. class Meta:
  78. ordering = ('name',)
  79. def __unicode__(self):
  80. return self.name
  81. # Person doesn't actually have a dependency on store, but we need to define
  82. # one to test the behaviour of the dependency resolution algorithm.
  83. def natural_key(self):
  84. return (self.name,)
  85. natural_key.dependencies = ['fixtures_regress.store']
  86. class Book(models.Model):
  87. name = models.CharField(max_length=255)
  88. author = models.ForeignKey(Person)
  89. stores = models.ManyToManyField(Store)
  90. class Meta:
  91. ordering = ('name',)
  92. def __unicode__(self):
  93. return u'%s by %s (available at %s)' % (
  94. self.name,
  95. self.author.name,
  96. ', '.join(s.name for s in self.stores.all())
  97. )
  98. __test__ = {'API_TESTS':"""
  99. >>> from django.core import management
  100. # Load a fixture that uses PK=1
  101. >>> management.call_command('loaddata', 'sequence', verbosity=0)
  102. # Create a new animal. Without a sequence reset, this new object
  103. # will take a PK of 1 (on Postgres), and the save will fail.
  104. # This is a regression test for ticket #3790.
  105. >>> animal = Animal(name='Platypus', latin_name='Ornithorhynchus anatinus', count=2, weight=2.3)
  106. >>> animal.save()
  107. ###############################################
  108. # Regression test for ticket #4558 -- pretty printing of XML fixtures
  109. # doesn't affect parsing of None values.
  110. # Load a pretty-printed XML fixture with Nulls.
  111. >>> management.call_command('loaddata', 'pretty.xml', verbosity=0)
  112. >>> Stuff.objects.all()
  113. [<Stuff: None is owned by None>]
  114. ###############################################
  115. # Regression test for ticket #6436 --
  116. # os.path.join will throw away the initial parts of a path if it encounters
  117. # an absolute path. This means that if a fixture is specified as an absolute path,
  118. # we need to make sure we don't discover the absolute path in every fixture directory.
  119. >>> load_absolute_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'absolute.json')
  120. >>> management.call_command('loaddata', load_absolute_path, verbosity=0)
  121. >>> Absolute.load_count
  122. 1
  123. ###############################################
  124. # Test for ticket #4371 -- fixture loading fails silently in testcases
  125. # Validate that error conditions are caught correctly
  126. # redirect stderr for the next few tests...
  127. >>> import sys
  128. >>> savestderr = sys.stderr
  129. >>> sys.stderr = sys.stdout
  130. # Loading data of an unknown format should fail
  131. >>> management.call_command('loaddata', 'bad_fixture1.unkn', verbosity=0)
  132. Problem installing fixture 'bad_fixture1': unkn is not a known serialization format.
  133. # Loading a fixture file with invalid data using explicit filename
  134. >>> management.call_command('loaddata', 'bad_fixture2.xml', verbosity=0)
  135. No fixture data found for 'bad_fixture2'. (File format may be invalid.)
  136. # Loading a fixture file with invalid data without file extension
  137. >>> management.call_command('loaddata', 'bad_fixture2', verbosity=0)
  138. No fixture data found for 'bad_fixture2'. (File format may be invalid.)
  139. # Loading a fixture file with no data returns an error
  140. >>> management.call_command('loaddata', 'empty', verbosity=0)
  141. No fixture data found for 'empty'. (File format may be invalid.)
  142. # If any of the fixtures contain an error, loading is aborted
  143. # (Regression for #9011 - error message is correct)
  144. >>> management.call_command('loaddata', 'bad_fixture2', 'animal', verbosity=0)
  145. No fixture data found for 'bad_fixture2'. (File format may be invalid.)
  146. >>> sys.stderr = savestderr
  147. ###############################################
  148. # Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn't
  149. # ascend to parent models when inheritance is used (since they are treated
  150. # individually).
  151. >>> management.call_command('loaddata', 'model-inheritance.json', verbosity=0)
  152. ###############################################
  153. # Test for ticket #7572 -- MySQL has a problem if the same connection is
  154. # used to create tables, load data, and then query over that data.
  155. # To compensate, we close the connection after running loaddata.
  156. # This ensures that a new connection is opened when test queries are issued.
  157. >>> management.call_command('loaddata', 'big-fixture.json', verbosity=0)
  158. >>> articles = Article.objects.exclude(id=9)
  159. >>> articles.values_list('id', flat=True)
  160. [1, 2, 3, 4, 5, 6, 7, 8]
  161. # Just for good measure, run the same query again. Under the influence of
  162. # ticket #7572, this will give a different result to the previous call.
  163. >>> articles.values_list('id', flat=True)
  164. [1, 2, 3, 4, 5, 6, 7, 8]
  165. ###############################################
  166. # Test for tickets #8298, #9942 - Field values should be coerced into the
  167. # correct type by the deserializer, not as part of the database write.
  168. >>> models.signals.pre_save.connect(animal_pre_save_check)
  169. >>> management.call_command('loaddata', 'animal.xml', verbosity=0)
  170. Count = 42 (<type 'int'>)
  171. Weight = 1.2 (<type 'float'>)
  172. >>> models.signals.pre_save.disconnect(animal_pre_save_check)
  173. ###############################################
  174. # Regression for #11286 -- Ensure that dumpdata honors the default manager
  175. # Dump the current contents of the database as a JSON fixture
  176. >>> management.call_command('dumpdata', 'fixtures_regress.animal', format='json')
  177. [{"pk": 1, "model": "fixtures_regress.animal", "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}}, {"pk": 2, "model": "fixtures_regress.animal", "fields": {"count": 2, "weight": 2.29..., "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}}, {"pk": 10, "model": "fixtures_regress.animal", "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}}]
  178. ###############################################
  179. # Regression for #11428 - Proxy models aren't included
  180. # when you run dumpdata over an entire app
  181. # Flush out the database first
  182. >>> management.call_command('reset', 'fixtures_regress', interactive=False, verbosity=0)
  183. # Create an instance of the concrete class
  184. >>> Widget(name='grommet').save()
  185. # Dump data for the entire app. The proxy class shouldn't be included
  186. >>> management.call_command('dumpdata', 'fixtures_regress', format='json')
  187. [{"pk": 1, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]
  188. ###############################################
  189. # Check that natural key requirements are taken into account
  190. # when serializing models
  191. >>> management.call_command('loaddata', 'forward_ref_lookup.json', verbosity=0)
  192. >>> management.call_command('dumpdata', 'fixtures_regress.book', 'fixtures_regress.person', 'fixtures_regress.store', verbosity=0, use_natural_keys=True)
  193. [{"pk": 2, "model": "fixtures_regress.store", "fields": {"name": "Amazon"}}, {"pk": 3, "model": "fixtures_regress.store", "fields": {"name": "Borders"}}, {"pk": 4, "model": "fixtures_regress.person", "fields": {"name": "Neal Stephenson"}}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]
  194. # Now lets check the dependency sorting explicitly
  195. # First Some models with pathological circular dependencies
  196. >>> class Circle1(models.Model):
  197. ... name = models.CharField(max_length=255)
  198. ... def natural_key(self):
  199. ... return self.name
  200. ... natural_key.dependencies = ['fixtures_regress.circle2']
  201. >>> class Circle2(models.Model):
  202. ... name = models.CharField(max_length=255)
  203. ... def natural_key(self):
  204. ... return self.name
  205. ... natural_key.dependencies = ['fixtures_regress.circle1']
  206. >>> class Circle3(models.Model):
  207. ... name = models.CharField(max_length=255)
  208. ... def natural_key(self):
  209. ... return self.name
  210. ... natural_key.dependencies = ['fixtures_regress.circle3']
  211. >>> class Circle4(models.Model):
  212. ... name = models.CharField(max_length=255)
  213. ... def natural_key(self):
  214. ... return self.name
  215. ... natural_key.dependencies = ['fixtures_regress.circle5']
  216. >>> class Circle5(models.Model):
  217. ... name = models.CharField(max_length=255)
  218. ... def natural_key(self):
  219. ... return self.name
  220. ... natural_key.dependencies = ['fixtures_regress.circle6']
  221. >>> class Circle6(models.Model):
  222. ... name = models.CharField(max_length=255)
  223. ... def natural_key(self):
  224. ... return self.name
  225. ... natural_key.dependencies = ['fixtures_regress.circle4']
  226. >>> class ExternalDependency(models.Model):
  227. ... name = models.CharField(max_length=255)
  228. ... def natural_key(self):
  229. ... return self.name
  230. ... natural_key.dependencies = ['fixtures_regress.book']
  231. # It doesn't matter what order you mention the models
  232. # Store *must* be serialized before then Person, and both
  233. # must be serialized before Book.
  234. >>> from django.core.management.commands.dumpdata import sort_dependencies
  235. >>> sort_dependencies([('fixtures_regress', [Book, Person, Store])])
  236. [<class 'regressiontests.fixtures_regress.models.Store'>, <class 'regressiontests.fixtures_regress.models.Person'>, <class 'regressiontests.fixtures_regress.models.Book'>]
  237. >>> sort_dependencies([('fixtures_regress', [Book, Store, Person])])
  238. [<class 'regressiontests.fixtures_regress.models.Store'>, <class 'regressiontests.fixtures_regress.models.Person'>, <class 'regressiontests.fixtures_regress.models.Book'>]
  239. >>> sort_dependencies([('fixtures_regress', [Store, Book, Person])])
  240. [<class 'regressiontests.fixtures_regress.models.Store'>, <class 'regressiontests.fixtures_regress.models.Person'>, <class 'regressiontests.fixtures_regress.models.Book'>]
  241. >>> sort_dependencies([('fixtures_regress', [Store, Person, Book])])
  242. [<class 'regressiontests.fixtures_regress.models.Store'>, <class 'regressiontests.fixtures_regress.models.Person'>, <class 'regressiontests.fixtures_regress.models.Book'>]
  243. >>> sort_dependencies([('fixtures_regress', [Person, Book, Store])])
  244. [<class 'regressiontests.fixtures_regress.models.Store'>, <class 'regressiontests.fixtures_regress.models.Person'>, <class 'regressiontests.fixtures_regress.models.Book'>]
  245. >>> sort_dependencies([('fixtures_regress', [Person, Store, Book])])
  246. [<class 'regressiontests.fixtures_regress.models.Store'>, <class 'regressiontests.fixtures_regress.models.Person'>, <class 'regressiontests.fixtures_regress.models.Book'>]
  247. # A dangling dependency - assume the user knows what they are doing.
  248. >>> sort_dependencies([('fixtures_regress', [Person, Circle1, Store, Book])])
  249. [<class 'regressiontests.fixtures_regress.models.Circle1'>, <class 'regressiontests.fixtures_regress.models.Store'>, <class 'regressiontests.fixtures_regress.models.Person'>, <class 'regressiontests.fixtures_regress.models.Book'>]
  250. # A tight circular dependency
  251. >>> sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Store, Book])])
  252. Traceback (most recent call last):
  253. ...
  254. CommandError: Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.
  255. >>> sort_dependencies([('fixtures_regress', [Circle1, Book, Circle2])])
  256. Traceback (most recent call last):
  257. ...
  258. CommandError: Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.
  259. # A self referential dependency
  260. >>> sort_dependencies([('fixtures_regress', [Book, Circle3])])
  261. Traceback (most recent call last):
  262. ...
  263. CommandError: Can't resolve dependencies for fixtures_regress.Circle3 in serialized app list.
  264. # A long circular dependency
  265. >>> sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])])
  266. Traceback (most recent call last):
  267. ...
  268. CommandError: Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized app list.
  269. # A dependency on a normal, non-natural-key model
  270. >>> sort_dependencies([('fixtures_regress', [Person, ExternalDependency, Book])])
  271. [<class 'regressiontests.fixtures_regress.models.Person'>, <class 'regressiontests.fixtures_regress.models.Book'>, <class 'regressiontests.fixtures_regress.models.ExternalDependency'>]
  272. ###############################################
  273. # Check that normal primary keys still work
  274. # on a model with natural key capabilities
  275. >>> management.call_command('loaddata', 'non_natural_1.json', verbosity=0)
  276. >>> management.call_command('loaddata', 'non_natural_2.xml', verbosity=0)
  277. >>> Book.objects.all()
  278. [<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>, <Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>, <Book: Permutation City by Greg Egan (available at Angus and Robertson)>]
  279. """}