通过models.ManyToManyField()实现
django-admin.py startproject csvt06
django-admin.py startapp blog
#
vim csvt06/settings.py
#数据库配置 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'csvt06.db', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': '', 'PASSWORD': '', 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } #应用配置 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', 'blog', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', )
#
vim blog/models.py
from django.db import models 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) #通过 models.ManyToManyField()实现 多对多。 authors = models.ManyToManyField(Author) def __unicode__(self): return self.name
#
python manage.py syncdb
#
squlit3 csvt
.tables
#
python manage.py shell
#
[]from blog.models import Author, Book
[]Author.objects.create(name='Aileo')
[]Author.objects.create(name='Lynn')
[]Author.objects.create(name='Rose')
[]Author.objects.create(name='Dev')
[]authors = Author.objects.all()
[]authors
#
b1 = Book()
b1.name = 'python book1'
b1.save()
#
aileo = Author.objects.get(name__exact='Aileo')
aileo
b1.authors.add(aileo)
#
b1.authors.add(authors[1])
b1.authors.all()
#
b1.authors.add(authors[2])
b1.authors.add(authors[3])
b1.authors.all()
#
b1.authors.remove(aileo)
b1.authors.all()
#
b1.authors.filter(name__exact='Lynn')
#
aileo.book_set.all()
aileo.book_set.add(b1)
#
aileo.book_set.create(name="python book2")
#
aileo.book_set.all()
#
books = Book.objects.all()
books
#
aileo.book_set.remove(books[0])
#
aileo.book_set.all()