1、文档教程链接:
https://docs.djangoproject.com/en/2.2/
2、下载命令:
pip3 install django
3、初识Django
3.1 设计模型:
Django无需数据库就可以使用,它提供了对象关系映射器,通过此技术,你可以使用Python代码来描述数据库结构。你可以使用强大的数据-模型语句来描述你的数据模型。
mysite/news/models.py¶
from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
def __str__(self):
return self.full_name
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
def __str__(self):
return self.headline
3.2 应用数据模型
运行Django命令行工具来创建数据库表
$ python manage.py migrate
接下来,你就可以使用一套便捷而丰富的PythonAPI访问你的数据,这些API是即时创建的,而不用显式的生成代码
# Import the models we created from our "news" app
>>> from news.models import Article, Reporter
# No reporters are in the system yet.
>>> Reporter.objects.all()
<QuerySet []>
# Create a new Reporter.
>>> r = Reporter(full_name='John Smith')
# Save the object into the database. You have to call save() explicitly.
>>> r.save()
# Now it has an ID.
>>> r.id
1