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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值