日期:2014-05-16  浏览次数:20418 次

Django-1.3的helloworld2,数据库的增删改查
Playing with the API
python\Django-1.3\docs\intro\tutorial01.txt的488页
接上一个helloworld
使用python manage.py shell 引入环境
>python manage.py shell
>>> from polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: Poll object>]
>>> import datetime
>>> p = Poll(question="What's up?", pub_date=datetime.datetime.now())
>>> p.save()
>>> p.id
2L
>>> p.question
"What's up?"
>>> p.pub_date
datetime.datetime(2011, 5, 13, 1, 12, 20, 687000)
>>> p.pub_date = datetime.datetime(2007, 4, 1, 0, 0)
>>> p.save()

跟hibernate似的
问题:能不能根据数据库反向生成module?
修改modules--->加__unicode__
from django.db import models
import datetime
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
            return self.question
    def was_published_today(self):
            return self.pub_date.date() == datetime.date.today()

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()
    def __unicode__(self):
            return self.choice

转成unicode
用str(p)显示
中文没搞懂?
#select语句
Poll.objects.filter(id=1)
#模糊查询
Poll.objects.filter(question__startswith='What')
Poll.objects.get(pub_date__year=2011)
Poll.objects.get(id=2)
#可以根据主键查
p = Poll.objects.get(pk=1)
p.was_published_today()
#查询所有
p.choice_set.all()
#插入语句
p.choice_set.create(choice='Not much', votes=0)
p.choice_set.create(choice='The sky', votes=0)
c = p.choice_set.create(choice='Just hacking again', votes=0)
#注意上面choice的model定义了外键
c.poll
#数量count(*)
p.choice_set.count()
#删除
c = p.choice_set.filter(choice__startswith='Just hacking')
c.delete()

不知道是否能提供原生sql的支持?,这种类似hibernate的东东在优化sql的时候肿是不太靠谱,还是单纯只考虑数据库简单点
定义了choice,就存在choice_set,是这样吗?

更多的api去看docs/topics/db/queries吧,我是不看了

如果是没数据,该model后
python manage.py reset core