djangoのquerysetでuniqueな値を取得する方法のメモ書き.
1.4系以降ではdistinctの引数でfield名を指定できるようになっているらしい.
ただしposgresql以外だとNotImplementedError('DISTINCT ON fields is not supported by this database backend')が出る.
http://django-docs-ja.readthedocs.org/en/latest/ref/models/querysets.html#distinct
一度取得してpythonで処理させてもよかったけどなんとなくDBにやらせたかったので調べたらvalues_listを使うといいらしい.
http://stackoverflow.com/questions/15626175/distinct-on-in-django
というわけで,MyModelのhogeフィールドのユニークな値を取るqsは以下のとおり.
MyModel.objects.all().values_list('hoge', flat=True).order_by('hoge').distinct()
order_by('hoge')を付けないと下のDBみたいにバラバラに入ってる場合にちゃんと取り除いてくれないので注意
id | hoge |
---|---|
1 | foo |
2 | bar |
3 | foo |
4 | piyo |