码迷,mamicode.com
首页 > 其他好文 > 详细

Django 笔记 模型数据的读取

时间:2016-02-10 06:42:51      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:模型   开发   读者   target   blank   

一开始我是根据 Django 1.8.2开发文档

http://python.usyiyi.cn/django/index.html

http://python.usyiyi.cn/django/ref/contrib/admin/index.html 进行实验,后来有读者说旧的教程坑比较多

所以我现在以官方文档

https://docs.djangoproject.com/en/dev/topics/db/models/

为主,进行实验


建立数据模型

Model.py

class Person(models.Model):
   SHIRT_SIZES = (
       (‘S‘, ‘Small‘),
       (‘M‘, ‘Medium‘),
       (‘L‘, ‘Large‘),
   )
   first_name = models.CharField(max_length=60)
   last_name = models.CharField(max_length=60)
   shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES , default=‘M‘)
def __str__(self):              # __unicode__ on Python 2
return self.first_name



技术分享

python manage.py makemigrations Sample
python manage.py migrate

执行模型同步到数据库,sqlite3

Pycharm 双击数据表,手动添加2条数据,点auto-commit右面的勾,发送数据写入数据库

技术分享


导入views,增加index 对应的执行程序

Urls.py

from django.conf.urls import url,patterns,include
from django.contrib import admin
from Sample import views as mysample
urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^index/$‘, mysample.index),
]


导入模块,读取所有的对象,制定模板

views.py

from django.shortcuts import render,render_to_response
from Sample.models import Person
# from Sample.models import
# Create your views here.

def index(request):
   emps = Person.objects.all()
return render_to_response(‘index.html‘,{‘emps‘:emps})


显示循环读取对象

template\index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% for emp in emps %}
<div>{{ forloop.counter }} {{ emp }}</div>
{% endfor %}
<div>total record {{emps.forloop.counter}}</div>
</body>
</html>


最后的显示结果,虽然难看了一点,但是至少数据库内容能够显示在页面,然后下一步是显示元祖或者多个对象,以及对数据库进行更新等操作

本文出自 “于昊(Pcdog)的博客” 博客,请务必保留此出处http://433266.blog.51cto.com/423266/1741447

Django 笔记 模型数据的读取

标签:模型   开发   读者   target   blank   

原文地址:http://433266.blog.51cto.com/423266/1741447

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!