- 模型文件:blog/models.py
from django.db import models
from django.utils import timezone
form django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
context = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
# 为了使print的结果更加有描述性
def __str__(self):
return self.title
- python manage.py makemigrations
- python manage.py sqlmigrate blog 0001 #查看migrate实际执行的sql命令
- python manage.py migrate
- python manage.py shell # 通过命令行操作模型
from blog.models import Post
from django.contrib.auth.models import User
User.objects.all()
User.objects.first()
User.objects.filter(username='testuser')
user = User.objects.filter(username='testuser').first()
user
user.id
user.pk #获取主键
user = User.objects.get(id=1)
post_1 = Post(title='blog 1', content='first post content!',author=user) # 创建post_1对象
post_1.save() # 将post_1对象保存到数据库中
Post.objects.all() # -> 如果打印结果:<QuerySet [<Post: Post object (1)>]> 打印的结果不容易查看,没有描述性。这是因为,我们在定义post模型的时候没有添加str方法。
post_2 = Post(title='blog 2', content='second post content!',author_id=user.id)
post_2.save()
Post.objects.all()
post = Post.objects.first()
post.content
post.date_posted
post.author
post.author.email
user.post_set.all() # 获取user的所有帖子
user.post_set.create(title='blog 3', content='third post content!') # 使用该用户创建帖子,并且会自动保存到数据库
Post.objects.all()
exit()
- blog/views.py中使用数据库
from django.shortcuts import render
from .models import Post
def home(request):
context = {
'posts': Post.objects.all() # 从数据库中查询Post数据
}
return render(request, 'blog/home.html', context)
def about(request):
return render(request, 'blog/about.html' {'title': 'About'})
- 模板中使用数据,并且使用filter控制日期的格式
<!--home.html-->
{% extends "blog/base.html" %}
{% block content %}
<h1>home page</h1>
{% for post in posts %}
<h3>{{ post.title }}</h3>
<!--使用 date:"F d, Y" 控制日期的显示格式-->
<p>By {{ post.author }} on {{ post.date_posted|date:"F d, Y"}}</p>
<p>{{ post.content }}</p>
{% endfor%}
{% endblock %}
- 编辑blog/admin.py将模型注册到后台管理页面,这样通过后台管理页面就能方便查看模型的数据
from django.contrib import admin
from .models import Post
admin.site.register(Post)
- https://localhost:8000/admin 和 https://localhost:8000/