django Django--Model中的ManyToManyField及页面显示

多对多的模式:

1. 新建项目

命令:django-admin.py startproject csvt06

2.建app

命令:python manage.py startapp blog

3.修改seting.py

数据库选择sqlite3

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.

        'NAME': 'csvt',                      # Or path to database file if using sqlite3.

        'USER': '',                      # Not used with sqlite3.

        'PASSWORD': '',                  # Not used with sqlite3.

        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.

        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.

    }

}

app打开admin 、添加blog

INSTALLED_APPS = (

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.sites',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    # Uncomment the next line to enable the admin:

     'django.contrib.admin',

    # Uncomment the next line to enable admin documentation:

    # 'django.contrib.admindocs',

'blog',

)

4.在blog下编辑models.py

from django.db import models

 

# Create your models here.

class Author(models.Model):

name = models.CharField(max_length =30)

 

def __unicode__(self):

return self.name

 

class Book(models.Model):

name = models.CharField(max_length =30)

authors = models.ManyToManyField(Author)         #创建多对多的关系

 

def __unicode__(self):

return self.name

5.在命令行执行命令:python manage.py syncdb

django Django--Model中的ManyToManyField及页面显示

 

表 blog_book_authors 中存放着表blog_book 和表blog_author的关联关系

用户名:km 密码:123456

6.运行交换shell命令:ipython manage.py shell

在交换窗口输入下面值,blog_author表中创建四个数据

from blog.models import Author ,Book

Author.objects.crea

Author.objects.create(name='Alen')

Author.objects.create(name='Ben')

Author.objects.create(name='Carl')

Author.objects.create(name='Dev')

authors = Author.objects.all()

authors

返回四个author的name

bl = Book()

b1.name = 'python book1'

b1.save()

取出Author中的Alen赋值给alen ‘name__exact’相当于sql 中的like

alen = Author.objects.get(name__exact = 'Alen')

alen

添加对应关系表

b1.authors.add(alen)

b1.authors.add(authors[1])

b1.authors.add(authors[2])

b1.authors.add(authors[3])

b1.author.all

删除对应关系表中的authors中的alen元素

b1.authors.remove(alen)

bl.authors.filter(name__exact='Carl')

 查看alen属性

alen.book_set.all()

添加对应关系,把alen和b1添加关联

alen.book_set.add(b1)

alen.book_set.all()

alen.book_set.create(name = 'python book2')

alen.book_set.all()

 

 

显示[<Book: python book1>,<Book:python book2>]

 

删除book中的第一个书

alen.book_set.remove(books[0])

shell中循环显示作者和他的书

for author in Author.objects.all():

    for book in author.book_set.all():

        print book

python book1

python book2

python book1

python book1

python book1

 

 

from blog.mobels import Author

alen = Author.objects.filter(name='Alen')

alen

通过shell添加一本书

alen.book_set.create(name='web1 book');

from blog.models import Book

books = Book.objects.all()

books

books[0]

b1 = books[0]

 

bl.authors.all()

7.在blog中添加views.py

# Create your views here.

from blog.models import Author,Book

from django.shortcuts import render_to_response

 

def show_author(req):

authors = Author.objects.all()

return render_to_response('show_author.html',{'authors':authors})

 

 

def show_book(req):

books = Book.objects.all()

 

return render_to_response('show_book.html',{'books':books})

8.在项目中添加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'^$', 'temp.views.home', name='home'),

    # url(r'^temp/', include('temp.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'^blog/show_author/$','blog.views.show_author'),

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

)

9.在blog下建文件夹templates,新建模板文件show_author.html 和show_book.html

show_author.html-----循环显示每个作者的书

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

 <head>

  <title> New Document </title>

  <meta name="Generator" content="EditPlus">

  <meta name="Author" content="">

  <meta name="Keywords" content="">

  <meta name="Description" content="">

 </head>

 

 <body>

  {% for author in authors%}

  <h3>{{author.name}}</h3>

      {% for book in author.book_set.all%}

 <li>{{book}}</li>

   

      {%endfor%}

  {%endfor%}

 </body>

</html>

show_book.html----循环每本书的作者

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

 <head>

  <title> New Document </title>

  <meta name="Generator" content="EditPlus">

  <meta name="Author" content="">

  <meta name="Keywords" content="">

  <meta name="Description" content="">

 </head>

 

 <body>

  {% for book in books%}

      <div>

     <h1>{{book.name}}</h1>

 {% for author in book.authors.all%}

     <li>{{author}}</li>

 {%endfor%}

 

 </div>

  {%endfor%}

 </body>

 

</html>

10.命令行运行自动服务器

命令:python manage.py runserver

访问地址:http://127.0.0.1:8000/blog/show_book/

django Django--Model中的ManyToManyField及页面显示

http://127.0.0.1:8000/blog/show_author/

django Django--Model中的ManyToManyField及页面显示

完成

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(django)