3

私は django query-fu のブラウンベルトにすぎません。ここには、私が知らない新しいトリックがいくつかあるかもしれません。

これが私のモデルです:

SCHOOL_TYPES = (('elementary', 'Elementary Schools'), ('middle', 'Middle Schools'), ('junior_high', 'Junior High Schools'), ('high_school', 'High Schools'), ('other', "Other"))

class School (BaseSlugModel):
    name=CharField(max_length=100)
    school_type = models.CharField(max_length=20, choices=SCHOOL_TYPES)

get_active_school_typesUI の目的で、 1 つ以上の学校が含まれる SCHOOL_TYPES タプルのサブセットを返す関数を作成したいと考えています。ブルートフォースよりも効率的にこれを行う方法はありますか?

編集:シメオンの答えに基づいた私の解決策は次のとおりです。

active_types = School.objects.values_list('school_type', flat=True).distinct()
return [ school_type for school_type in SCHOOL_TYPES if school_type[0] in active_types]
4

1 に答える 1

2

distinctQuerySet のメソッドを使用できます。

School.objects.order_by('school_type').distinct('school_type')

これにより、Python コードの代わりにデータベースが処理できるようになります。フィールド名を に渡すdistinctことは、PostgreSQL を使用している場合にのみ機能することに注意してください。

次のものも使用できますvalues_list

School.objects.values_list('school_type', flat=True).distinct()

これにより、値のリストが返されます。

于 2012-07-16T13:18:00.350 に答える