Djangoでビューを使ってみる
2006年03月15日(水) 21:59
データベースのビューはO/R Mapperで常に懸念事項としてあがってくる。
Djangoの場合もmodelの定義からデータベース構造ができあがる仕組みなので、ビューを使うのは一般的ではない。
ただ、実際はオブジェクトとして全部引っ張り出してから集計とかを行うのはばかげているので、ビューを扱って問題がないかを確認してみたというわけ。
実際に使っているのは、エントリのある月を一覧するところ(だってDjango本家のアーカイブはテンプレートに直に書いてあるんだもん。見間違え?)。
CREATE VIEW文は次のようにした。
create view djablog_archives as
select
yearmonth as id,
yearmonth as yearmonth
from (
select
distinct(to_char(create_date, 'yyyymm')) as yearmonth
from djablog_entry
order by yearmonth desc
) archives
order by id desc
; わざわざidという項目としても出力しているのは、Djangoがidを欲しがるだろうとの勝手な思いこみ。
みての通り、只単に年月をユニークに出しているだけ。
modelの方は、これまた汚いけど、こうなっている。
2006/03/17 追記
辞書を使えとの指摘。確かに!
class Archives(models.Model) :
yearmonth = models.CharField(maxlength=6, blank=False)
def get_path(self) :
month = ''
year = self.yearmonth[0:4]
mm = self.yearmonth[4:6]
print mm
if mm == '01' :
month = 'jan'
elif mm == '02' :
month = 'feb'
elif mm == '03' :
month = 'mar'
elif mm == '04' :
month = 'apr'
elif mm == '05' :
month = 'may'
elif mm == '06' :
month = 'jun'
elif mm == '07' :
month = 'jul'
elif mm == '08' :
month = 'aug'
elif mm == '09' :
month = 'sep'
elif mm == '10' :
month = 'oct'
elif mm == '11' :
month = 'nov'
else :
month = 'dec'
return '/%s/%s/' % (year, month)
Archive表示が/yyyy/mon/を求めるので、変換している。
VIEWで出力する際にmonで出力でもいいんだけど、並べ替えが面倒なので、modelでmonに無理矢理変換しちゃった。
あとは、カスタムtagを作ってブログのベースで呼び出してぐるぐるすると、トップページとかに出ているArchivesができあがる。
Comments
[2006年03月16日(木) 20:38]
jbking
連想配列使いましょうよぅ。
定義
mc = {'01': 'jan', '02': 'feb', 〜 '12': 'dec'}
利用
month = mc[mm]
[2006年03月16日(木) 22:15]
makoto
おぉ、確かに!
辞書使うべきだなぁ。
なんでif elifにしたのか自分でもわからない。
[2006年03月16日(木) 22:54]
mopemope
generic-view使わないの??
ちなみにgeneric-viewだと
blog_dict = {
'queryset': Post.objects.all(),
'date_field': 'date',
'month_format': '%m'
}
date_base = 'django.views.generic.date_based.'
urlpatterns = patterns('',
(r'^(?P<year>\d{4})/(?P<month>\w{1,2})/$', date_base+'archive_month', blog_dict),
)
集計に使用する日付フィールドの指定やフォーマットも指定できます。
他にも
そのまま返してmonth_format指定すれば一発かと。
by genric-viewより
#お好みであわせてください
month_format=%m
date = datetime.date(*time.strptime(year+month, '%Y'+month_format)[:3])
[2006年03月17日(金) 01:06]
makoto
generic-viewでやってますが、month_formatってのは使ってないっすね。
月表示は英文字で行いたいのでこのままにしますが、month_format覚えとこ。
未だドキュメントをイマイチ読んでいない(コードも余り見ていないってことだ)。
うひー。どんどんさらしていろいろつっこんでもらおう。
