models.py
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
def __str__(self):
return self.question_text
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
def __str__(self):
return self.choice_text
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
python shell
from polls.models import Choice, Question
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id #输出:1
q.question_text #输出:What's new?
q.pub_date #输出:datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
q.question_text = "What's up?"
q.save()
Question.objects.all() #输出:<QuerySet [<Question: What's up?>]>
Question.objects.filter(id=1) #输出:<QuerySet [<Question: What's up?>]>
Question.objects.filter(question_text__startswith = 'What') #输出:<QuerySet [<Question: What's up?>]>
Question.objects.get(pub_date__year = timezone.now().year) #输出:<Question: What's up?>
Question.objects.get(id=2) #输出:报错,因为只有1条记录
Question.objects.get(pk=1) #输出:<Question: What's up?>
q = Question.objects.get(pk=1)
q.was_published_recently() #输出:True
q = Question.objects.get(pk=1)
q.choice_set.all() #输出:<QuerySet []>
q.choice_set.create(choice_text='Not much', votes=0) #输出:<Choice: Not much>
q.choice_set.create(choice_text='The sky', votes=0) #输出:<Choice: The sky>
c = q.choice_set.create(choice_text='Just hacking again', votes=0)
c.question #输出:<Question: What's up?>
q.choice_set.all()
#输出:<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
q.choice_set.count() #输出:3
Choice.objects.filter(question__pub_date__year=current_year)
#输出:<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
c = q.choice_set.filter(choice_text__startswith='Just hacking')
c.delete() #删除该记录
本文介绍如何使用 Django 创建一个投票应用,包括模型定义、数据操作及查询。演示了 Question 和 Choice 模型的创建过程,以及通过 Python shell 进行数据增删改查的具体方法。

被折叠的 条评论
为什么被折叠?



