django mysql数据显示_django 数据库操作及页面显示

本文介绍了如何在Django中插入和查询MySQL数据库数据,包括使用shell、模型方法以及管理器方式。同时,展示了如何通过定义模型的__unicode__方法自定义对象的显示方式。最后,详细说明了如何在页面上显示数据库数据,包括URL配置、视图函数的编写、模板的创建和使用。
摘要由CSDN通过智能技术生成

插入数据方法

方法一:

ipython manage.py shell

from blog.models import Employee

emp = Employee()  创建实例对象

emp.name = 'Alen'

emp.save()

从数据库查看数据是否入库

select *from blog_employee

方法二:直接在构造方法中把值传入

emp = Employee(name="tom")

emp.save()

方法三:类对象管理方式

Employee.objects.cre

Employee.objects.creat(name = "max")

emp.save()

或者

emp = Employee.objects.create(name ="km")

emp.save()

-----------------------------------------------

查看数据

emps = Employee.objects.all()

emps

emps[0].id

emps[0].name

方法二:

在models.py 中添加一个方法

当我们的对象以字符串展现的时候,name显示出来

from django.db import models

class Employee(models.Model):

name = models.CharField(max_length=100)

def __unicode__(self):

return self.name

重新打开ipython manage.py shell

from blog.models import Employee

emps = Employee.objects.all()

emps

显示每个字段的名称

------------------------------------------------------

在页面上显示数据库数据

1.在url.py 中添加

from django.conf.urls.defaults import patterns, include, url

# Uncomment the next two lines to enable the admin:

# from django.contrib import admin

# admin.autodiscover()

urlpatterns = patterns('',

# Examples:

# url(r'^$', 'csvt03.views.home', name='home'),

# url(r'^csvt03/', include('csvt03.foo.urls')),

# Uncomment the admin/doc line below to enable admin documentation:

# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

# Uncomment the next line to enable the admin:

# url(r'^admin/', include(admin.site.urls)),

url(r'^index/$','blog.views.index'),

)

2.在views.py中添加

# Create your views here.

from django.shortcuts import render_to_response

from blog.models import Employee

def index(req):

emps = Employee.objects.all()

return render_to_response('index.html',{'emps':emps})

#return render_to_response('index.html',{'dic':dic,'user':user})

3.在项目blog中添加文件夹

mkdir templates

在templates文件夹中添加一个index.html文件

/p>

"http://www.w3.org/TR/html4/loose.dtd">

New Document

{{emps}}

{% for emp in emps%}

{{forloop.counter}}{{emp}}

{% endfor%}

共有{{empslength}}记录

4.运行python manage.py runserver  就能查看到数据库返回内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值