Django模型:多對多關係模型

通過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()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章