Django 데이터베이스 쿼리

23077 단어 django

Django 데이터베이스 쿼리
 
 
birthday__year=2006 
headline__startswith='What'     headline__startswith like 'What%'
headline__endswith='What'     headline__startswith like '%What'
birthday__gte=datetime.now()     birthday__gte >= datetime.now()
birthday__lte=datetime.now()     birthday__gte <= datetime.now()
pk__gt=14     pk>14
name__icontains="food"     name like "%food%"
headline__exact="Man bites dog"     headline = 'Man bites dog';
name__iexact="beatles blog"   name="beatles blog"   ,      
name__isnull=True     name null  
pk__in=[1,4,7]     id in{1,4,7} 

   
many 
e = Entry.objects.get(id=2) 
print e.blog

one 
b = Blog.objects.get(id=1)
b.entry_set.all()
b.entry_set.count() 

 
 
 
#!/usr/bin/python
#coding:utf-8

from django.shortcuts import render;
from django.shortcuts import render_to_response;
from django.http import HttpResponse;
from django.template import loader,Context, Template;
from django.http import HttpResponseRedirect;
from django.views.decorators.csrf import csrf_exempt;
import time, datetime;
from django.db import connection,transaction;

from blog.models import Blog;
from blog.models import Entry;
from blog.models import Author;
from blog.models import AuthorBlog;


def saveBlog(request):
    try:
        blog=Blog();
        blog.name="python";
        blog.tagline="Python      、    、               。  20  90   Python      ,                  Web  。";
        blog.save();
        return HttpResponse("save blog success");
    except BaseException, e:
        return HttpResponse("save blog failure:"+e);
        
def updateBlog(request):
    try:
        blog=Blog.objects.get(id=4);
        blog.tagline="Python      、    、               。";
        blog.save();
        return HttpResponse("update blog success");
    except BaseException, e:
        return HttpResponse("update blog failure:"+e);

def delBlog(request):
    try:
        blog=Blog.objects.get(id=4);
        #blog.delete();
        return HttpResponse("delete blog success");
    except BaseException, e:
        return HttpResponse("delete blog failure:"+e);

###     ###
def saveEntry(request):
    try:
        blog=Blog.objects.get(id=4); #python
        entry=Entry();   
        entry.headline="django";
        entry.body_text="Django         Web    , Python  。";
        entry.pub_date=datetime.date.today();
        entry.blog=blog;
        entry.save();
        return HttpResponse("save entry success");
    except BaseException, e:
        return HttpResponse("save entry failure:"+e);

###     ###
def saveAuthorBlog(request):
    try:
        author=Author.objects.get(id=1);
        blog=Blog.objects.get(id=4);
        ab=AuthorBlog();
        ab.author=author;
        ab.blog=blog;
        ab.created_at=datetime.date.today();
        ab.save();
        return HttpResponse("save AuthorBlog success");
    except BaseException, e:
        return HttpResponse("save AuthorBlog failure:"+e);
      
def queryBlog(request):
    #       
    blogs = Blog.objects.all();
    for blog in blogs:
        print blog.name;
    print "=======";
    
    #     
    entrys=Entry.objects.all();
    for entry in entrys:
        print entry.headline+", "+entry.blog.id+", "+entry.blog.name;
    print "=======";
    
    return HttpResponse("queryBlog");
    
###             ###
def rawBlog(request):
    raw_sql = 'select * from blog_Blog';
    blogs=Blog.objects.raw(raw_sql); #xx.objects.raw()    sql
    print blogs;
    for blog in blogs:
        print blog.name;
    print "======";
    
    raw_sql = 'select * from blog_Blog o where o.name=%s'; #   
    blogs=Blog.objects.raw(raw_sql, ["j2ee"]); #xx.objects.raw()    sql
    print blogs;
    for blog in blogs:
        print blog.name;
    return HttpResponse("rawBlog");
    
def sqlBlog(request):
    cursor=connection.cursor(); #      (cursor)  
    
    #    
    cursor.execute('update blog_Blog set name="hadoop168" where id=%s', [1]); #  sql  
    transaction.commit_unless_managed(); #      
    
    #    
    cursor.execute('select * from blog_Blog where id=%s', [1]);
    blogs = cursor.fetchone(); #    #raw = cursor.fetchall();          
    for blog in blogs:
        print blog;
    print "======";
    
    cursor.execute('select * from blog_Blog');
    blogs = cursor.fetchall(); #          
    for blog in list(blogs):
        print str(blog[0])+", "+blog[1]+", "+blog[2];
    print "======";
    
    return HttpResponse("sqlBlog");

def querySqlBlog(request):
    sql="select b.name as blog_name, e.headline from blog_Blog b, blog_Entry e where b.id=e.blog_id";
    cursor=connection.cursor(); #      (cursor)  
    cursor.execute(sql);
    blogs = cursor.fetchall(); #          
    
    records=[]
    for blog in blogs:
        dic={}
        dic['blog_name']=blog[0]
        dic['headline']=blog[1]
        records.append(dic);
    
    for record in records:
        print record["blog_name"]+", "+record["headline"];
    return HttpResponse("sqlBlog");
    
def searchBlog(request):
    #       
    #blogs = Blog.objects.all(); #  all()             
    
    #       ,        : 
    #fileter()            QuerySet,     (=)
    #exclude()             QuerySet,      (!=)
    
    #blogs=Blog.objects.filter(name='python');    :slect * from blog_Blog where name='python' 
    #   Blog.objects.all().filter(name='python'),      ,all()             。 
    blogs=Blog.objects.filter(name='python');
    for blog in list(blogs):
        print str(blog.id)+", "+blog.name+", "+blog.tagline;
    print "======";
    
    return HttpResponse("searchBlog");
    
    
    
    

좋은 웹페이지 즐겨찾기