如果要使用Django Shell,就必须使用下面的这个命令:python3 manage.py shell
导入polls.models模块from polls.models import Question, Choice
显示所有数据:Question.objects.all()
导入时间模块from django.utils import timezone
创建一个Question对象q = Question(question_text='What's new?', pub_date=timezone.now())
保存对象到数据库,可以使用save()函数。q.save()现在数据库表格有一个ID字段。
7、通过对象属性引用来读取数据。q.idq.question_textq.pub_date
再编辑polls/models.py,让数据对象有返回值。import datetimefrom django.db import modelsfrom django.utils import timezone# Create your models here.class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1)class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text让models.py的修改写入到数据库,python manage.py migrate
让models.py的修改写入到数据库,使用如下命令:python manage.py migrate