Help us understand the problem. What is going on with this article?

field値での重複削除

More than 3 years have passed since last update.

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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away