多语言展示
当前在线:153今日阅读:176今日分享:34

Django1.7中文入门教程:[8]Django的API使用

使用shell来测试django数据库的操作。并做一个app里的models设置。
方法/步骤
1

如果要使用Django Shell,就必须使用下面的这个命令:python3 manage.py shell

2

导入polls.models模块from polls.models import Question, Choice

3

显示所有数据:Question.objects.all()

4

导入时间模块from django.utils import timezone

5

创建一个Question对象q = Question(question_text='What's new?', pub_date=timezone.now())

6

保存对象到数据库,可以使用save()函数。q.save()现在数据库表格有一个ID字段。

7

7、通过对象属性引用来读取数据。q.idq.question_textq.pub_date

8

再编辑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

9

让models.py的修改写入到数据库,使用如下命令:python manage.py migrate

推荐信息