ContentTypesが便利だとかの解説

ちょっと前に書いたContentTypesの話の補足。
ContentTypeとマルチテーブル継承を使う - 偏った言語信者の垂れ流し
これの何が便利かというと、継承元のモデルであるItemNodeから継承先のモデルにアクセスできること。

In [6]: for node in ItemNode.objects.all():
   ...:     if node.model_class is Bookmark:
   ...:         print 'bookmark: %s' % node.original.url
   ...:     elif node.model_class is Feed:
   ...:         print 'feed: %s feeds' % len(node.original.feeds)
   ...:     elif node.model_class is Category:
   ...:         print 'category: %s' % node.name
   ...:     else:
   ...:         print 'node: %s' % node.name
   ...:
   ...:
bookmark: http://tokibito.orz.hm/
bookmark: http://d.hatena.ne.jp/nullpobug/
category: 巡回
category: ポータル
category: Python
category: Delphi
feed: 10 feeds
feed: 10 feeds
bookmark: http://www.yahoo.co.jp/
bookmark: http://homepage1.nifty.com/ht_deko/
bookmark: http://www.google.co.jp/
bookmark: http://jquery.com/
bookmark: http://www.codegear.com/jp/
bookmark: http://www.python.org/

ItemNodeはいつもどおり、allやfilterメソッドで取得できる。
node.model_classでオリジナルのクラスを取得できる。
node.originalでオリジナルのオブジェクトにアクセスできる。
この方法を使えるとソースコードはかなりシンプルになる。データベースだけを見た場合は少しわかりにくい構造になってるかも。