日期:2014-05-16 浏览次数:20534 次
>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()
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#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()