Login

Tag "database"

Snippet List

Ordered items in the database

First off: This snippet is more or less obsoleted by [snippet #259](/snippets/259/). The way that snippet #259 uses feels cleaner and more usable. It is basically the same code but the magic works a little bit different. In case you prefer this way, I've left this snippet as-is. Maybe you know this problem: you have some objects in your database and would like to display them in some way. The problem: the Django ORM does not provide any way to sort model instances by a user-defined criterion. There was already a plug-in in SQLAlchemy called [orderinglist](http://www.sqlalchemy.org/docs/plugins.html#plugins_orderinglist), so implementing this in Django was basically not a big deal. Usage is (due to use of meta-classes) quite simple. It is recommended to save this snippet into a separate file called `positional.py`. To use it, you only have to import `PositionalSortMixIn` from the `positional` module and inherit from it in your own, custom model (but *before* you inherit from `models.Model`, the order counts).

  • db
  • orm
  • database
  • plugin
  • mixin
Read More

Database migration and dump/load script

I once needed to convert a Django project from PostgreSQL to SQLite. At that time I was either unaware of manage.py dumpdata/loaddata or it they didn't yet exist. I asked for advice on the #django IRC channel where ubernostrum came up with this plan: simple process: 1) Select everything. 2) Pickle it. 3) Save to file. 4) Read file. 5) Unpickle. 6) Save to db. :) Or something like that. First I thought it was funny, but then started to think about it and it made perfect sense. And so dbpickle.py was born. I've used this script also for migrating schema changes to production databases. For migration you can write plugins to hook on dbpickle.py's object retrieval and saving. This way you can add/remove/rename fields of objects on the fly when loading a dumped database. It's also possible to populate new fields with default values or even values computed based on the object's other properties. A good way to use this is to create a database migration plugin for each schema change and use it with dbpickle.py to migrate the project. See also [original blog posting](http://akaihola.blogspot.com/2006/11/database-conversion-django-style.html) and [my usenet posting](http://groups.google.com/group/django-users/browse_thread/thread/6a4e9781d08ae815/c5c063a288483e07#c5c063a288483e07) wondering about the feasibility of this functionality with manage.py dumpdata/loaddata. See [trac site](http://trac.ambitone.com/ambidjangolib/browser/trunk/dbpickle/dbpickle.py) for version history.

  • dump
  • database
  • migration
  • load
  • pickle
Read More

47 snippets posted so far.