models.py示例
from django.db import models # Create your models here. class Post(models.Model): title = models.CharField(max_length=140) #Django会在表中自动添加字段: "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT body = models.TextField() date = models.DateTimeField() def __str__(self): return self.title
迁移到数据库
1 makemigrations blog 修改models后,创建新的migrations 2 migrate 提交migrations,或者显示他们的状态 其他 sqlmigrate blog 0001 显示某一个migration的SQL状态(创建table等操作) showmigrations 列出project的所有migrations
可以用python manage.py shell测试
from blog.models import Post p = Post(1, ‘first blog‘, ‘This is my first blog.‘, ‘2016-04017‘)
p.save()
Post.objects.all()
在模板中使用Model中的数据
#blog/urls.py
from django.conf.urls import url, include from django.views.generic import ListView, DetailView #使用通用视图 from blog.models import Post urlpatterns = [ url(r‘^$‘, ListView.as_view(queryset=Post.objects.all().order_by("-date")[:25]), template_name="blog/blog.html"),
url(r‘^(?P<pk>\d+)$‘, DetailView.as_view(model=Post, template_name=‘blog/post.html‘)), #(?P<name>pattern)
#<pk>:primary key,这里就是‘id‘,获得对象post=Post.objects.get(pk=\d+)并传入post.html中
]
#blog/templates/blog/blog.html {% extends ‘blog/basic.html‘ %} {% block content %} {% for post in object_list %} <h5>{{ post.date|date:‘Y-m-d‘ }}<a href=‘/blog/{{ post.id }}‘> {{ post.title }}</a></h5> {% endfor %} {% endblock %}
{% extends ‘blog/basic.html‘ %} {% block content %} <h3>{{ post.title }}</h3> <h6>on {{ post.date }}</h6> <p>{{ post.body | safe | linebreaks }}</p> #safe模式:可以使用html标签,否则原型输出; linebreaks 保持换行
{% endblock %}
关于外键
class Album(models.Model): ... class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) ... # Song是依赖于Album的,on_delete=models.CASCADE即当删除一个Album时,依赖它的Song也会一起删除
# 通过Album访问Song:
album = Album()
song = album.song_set.all() .get() .filter .count()
#通过Song访问Album:
song = Song()
album = song.album.all() get filter count...
原文:http://www.cnblogs.com/roronoa-sqd/p/4916150.html