計劃把 文章全部轉移至 這裡,而本 Blogger 站台的文章近 500 篇,我預計在 2014-12-31 前移轉完畢,完成後 將只作代轉服務,一律把舊連結如 轉成 ,敬請舊雨新知互相走告。


何岳峰 敬上

2007年5月8日 星期二

Use django's models without running web server

>>This article also posts on django-users<<

Because i can't find related post here, so i post this example. maybe someone else need.

Sometimes, you just want to use the useful models of django without thinking any sql statement.
Maybe you want to run a script to know which user's birthday in your database is today,
this little job should not run in the It should run in the cron table of linux os every day,
so that your users can receive birthday card from your system.

this example is so easy, all you know is loading the correctly.
Your script must place in your django project's directory.

script example:

1 #!/usr/bin/env python
2 # -*- coding: utf8 -*-
4 import settings
5 from import setup_environ
6 setup_environ(settings)
7 # before do something else,
8 # the there lines above here is your first operation.
10 from django.db.models import get_model
11 from datetime import date
13 if __name__ == '__main__':
15 # the 'tmp' is your project's name,
16 # and this script must place in the 'tmp' directory.
17 # the 'person' is your model's name.
18 Person = get_model('tmp', 'person')
20 # when you get the model,
21 # you can use it just like you use it in the
22 P = Person(name='hoamon', birth=date(1977, 10, 18))
25 for p in Person.objects.all():
26 if p.birth == date(1977, 10, 18):
27 print
29 for p in Person.objects.filter(birth=date(1977, 10, 18)):
30 print

now you can put /somepath/tmp/ in the cron table.

1 則留言:

  1. After i posted this comment on django-users, i found the keyword is "use models outside django", not "without web server".



Related Posts Plugin for WordPress, Blogger...