您的位置:首页 > 数据库

Django学习笔记3-数据库操作

2015-12-29 13:34 585 查看
Django Model

* 每一个Django Model都继承自django.db.models.Model

* 在Model中每个属性attribute都代表一个database field

* 通过Django Model API 可以执行数据增删改查,无须写sql语句

建好一个项目后,数据库的位置:project_name/project_name/settings.py 可以查看和修改数据库设置。默认使用sqlite3 如需使用其他数据库在此另作配置。

数据库准备:建表、同步

创建models

编辑settings.py文件,添加一个数据表(形式上是一个类)

class Article (models.Model):
title = models.CharField(max_length = 100)
category = models.CharField(max_length=50, blank=True)
date_time = models.DateTimeField(auto_now_add=True)
content = models.TextField(blank=True,null=True)

def __unicode__(self):
#use title to represent Ariticle object.
return self.title

class Meta:  #time decending.
ordering = ['-date_time']


同步数据库

python mange.py migrate

python mange.py makemigration #有时要先运行这条再运行上面的命令

注意:一定要同步,不然识别不到Article类

数据库使用-Django shell

>>>from article.models import Article


>>>Article.objects.create(title='Hello World', category='Python', content='insert data to database.')


<Article: Hello World>


>>>Article.objects.create(title='Django Blog Leanring', category ='python',content='Django Simple Blog guide.')


<Article: Django Blog Leanring>


查-all和get

all查看全部对象

>>>Article.objects.all()


[<Article: Django Blog Leanring>, <Article: Hello World>]


get按索引查看元素,索引从1开始

>>>first=Article.objects.get(id=1)


>>>first.title


u'Hello World'


>>>first.date_time


datetime.datetime(2015, 12, 28, 9, 5, 50, 308000, tzinfo=<UTC>)


>>> first.content ='Hello world, how are you?'


>>> first.content


u'Hello world, how are you?'


>>> first.delete()


(1, {u'article.Article': 1})


>>> Article.objects.all()


[<Article: Django Blog Leanring>]


更多API参考官方文档。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: