LoginSignup
17
12

More than 5 years have passed since last update.

field値での重複削除

Posted at

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
17
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
12