Django简单数据库查询例子

来源:互联网 发布:sql limit offset用法 编辑:程序博客网 时间:2024/05/18 12:42

/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> 

 

Django简单数据库查询例子


白及说:

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

参考:

http://blog.sina.com.cn/s/blog_548b0a230100ietf.html

0 0
原创粉丝点击