dumpscript.rst 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. dumpscript
  2. ==========
  3. :synopsis: Generates a standalone Python script that will repopulate the database using objects.
  4. The `dumpscript` command generates a standalone Python script that will
  5. repopulate the database using objects. The advantage of this approach is that
  6. it is easy to understand, and more flexible than directly populating the
  7. database, or using XML.
  8. Why?
  9. ----
  10. There are a few benefits to this:
  11. * less drama with model evolution: foreign keys handled naturally without IDs,
  12. new and removed columns are ignored
  13. * edit script to create 1,000s of generated entries using for loops, generated
  14. names, python modules etc.
  15. For example, an edited script can populate the database with test data::
  16. for i in xrange(2000):
  17. poll = Poll()
  18. poll.question = "Question #%d" % i
  19. poll.pub_date = date(2001,01,01) + timedelta(days=i)
  20. poll.save()
  21. Real databases will probably be bigger and more complicated so it is useful
  22. to enter some values using the admin interface and then edit the generated
  23. scripts.
  24. Features
  25. --------
  26. * *ForeignKey* and *ManyToManyFields* (using python variables, not object IDs)
  27. * Self-referencing *ForeignKey* (and M2M) fields
  28. * Sub-classed models
  29. * *ContentType* fields and generic relationships
  30. * Recursive references
  31. * *AutoFields* are excluded
  32. * Parent models are only included when no other child model links to it
  33. * Individual models can be referenced
  34. How?
  35. ----
  36. To dump the data from all the models in a given Django app (`appname`)::
  37. $ ./manage.py dumpscript appname > scripts/testdata.py
  38. To dump the data from just a single model (`appname.ModelName`)::
  39. $ ./manage.py dumpscript appname.ModelName > scripts/testdata.py
  40. To reset a given app, and reload with the saved data::
  41. $ ./manage.py reset appname
  42. $ ./manage.py runscript testdata
  43. Note: Runscript needs *scripts* to be a module, so create the directory and a
  44. *__init__.py* file.
  45. Caveats
  46. -------
  47. Naming conflicts
  48. ~~~~~~~~~~~~~~~~
  49. Please take care that when naming the output files these filenames do not
  50. clash with other names in your import path. For instance, if the appname is
  51. the same as the script name, an importerror can occur because rather than importing
  52. the application modules it tries to load the modules from the dumpscript file itself.
  53. Examples::
  54. # Wrong
  55. $ ./manage.py dumpscript appname > dumps/appname.py
  56. # Right
  57. $ ./manage.py dumpscript appname > dumps/appname_all.py
  58. # Right
  59. $ ./manage.py dumpscript appname.Somemodel > dumps/appname_somemodel.py