您的位置:首页 > 数据库

Django简单数据库查询例子

2017-03-22 19:08 351 查看
/mysite/books/models.py

from django.db import models

# Create your models here.

class Publisher(models.Model):

    name = models.CharField(max_length=30)

    address = models.CharField(max_length=50)

    city = models.CharField(max_length=60)

    state_province = models.CharField(max_length=30)

    country = models.CharField(max_length=50)

    website = models.URLField()

    def __unicode__(self):

        return self.name

 

/mysite/settings.py

DATABASE_ENGINE = 'mysql'         

DATABASE_NAME = 'test'            

DATABASE_USER = 'root'            

DATABASE_PASSWORD = '778899'  

DATABASE_HOST = '127.0.0.1'  

DATABASE_PORT = 3306       

TEMPLATE_DIRS = (

       'e:/myfirstsite/template',

)

INSTALLED_APPS = (

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.sites',

    'myfirstsite.books',

)

 

/mysite/view.py

import MySQLdb

from books.models import Publisher

def book_list(request):  

    db = MySQLdb.connect(user='root', db='test', passwd='778899', host='localhost')  

    cursor = db.cursor()  

    cursor.execute('SELECT name FROM books_publisher ORDER BY name')  

    #names = [row[0] for row in cursor.fetchall()]

    names = Publisher.objects.all()

    db.close()  

    return render_to_response('book/book_list.html', {'names': names}) 

 

/mysite/urls.py

from mysite.view import book_list

import MySQLdb

urlpatterns = patterns('',  

(r'^book/$',book_list),               



/mysite/template/book/book_list.html

{% extends 'book\base.html' %}

{% block title %}title: book_lib{% endblock %}

{% block content %}

<table> 

  <tr><th>book</th><th>address</th><th>city</th></tr> 

   {% for m in names %}  

   <tr>  

     <td >  {{ m.name }}    </td> 

     <td > {{ m.address }}  </td>

     <td >  {{ m.city }}    </td>  

   </tr>  

   {% endfor %}  

</table> 

{% endblock %}

 

/mysite/template/book/base.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> 

<html lang="en"> 

<head> 

    <title>{% block title %}{% endblock %}</title> 

</head> 

<body> 

    <h1>My book Site</h1> 

    <hr>

    {% block content %}{% endblock %}   

    {% block footer %}  

    <p>Thanks for visiting my site.</p> 

    {% endblock %} 

</body> 

</html> 

 





白及说:

例子很简单,提供一个思路不错!

参考:

http://blog.sina.com.cn/s/blog_548b0a230100ietf.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: