Django笔记-数据库操作(多对多关系)

1、项目结构

2、关键代码:

data6.settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'data6',
        'USER':'root',
        'PASSWORD':'passwd',
        'PORT':'3306',
        'HOST':'localhost',
    }
}
View Code

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)
    authors = models.ManyToManyField(Author)
        def __unicode__(self):
        return self.name
View Code

3、自动生成的数据表

4、Django通过shell进行的操作:

首先导入models里创建的对象:

>>> from blog.models import Author,Book

 

添加author

>>> Author.objects.create(name='Tom01')

<Author: Tom01>

>>> Author.objects.create(name='Tom02')

<Author: Tom02>

>>> Author.objects.create(name='Tom03')

<Author: Tom03>

>>> Author.objects.create(name='Tom04')

<Author: Tom04>

 

查看生成的author

>>> authors = Author.objects.all()

>>> authors

[<Author: Tom01>, <Author: Tom02>, <Author: Tom03>, <Author: Tom04>]

 

添加一本书Python book1

>>> b1 = Book()

>>> b1.name = 'Pyhon book1'

>>> b1.save()

 

获取一个作者

>>> tom2 = Author.objects.get(name__exact='Tom02')

>>> tom2

<Author: Tom02>

 

Python book1添加作者

>>> b1.authors.add(tom2)

>>> b1.authors.add(authors[3])

 

b1的作者

>>> b1.authors.all()

[<Author: Tom02>, <Author: Tom04>]

>>> b1.authors.add(authors[2])

 

去掉一个作者

>>> b1.authors.remove(authors[3])

>>> b1.authors.all()

[<Author: Tom02>]

 

>>> b1.authors.add(authors[0])

>>> b1.authors.all()

[<Author: Tom01>, <Author: Tom02>]

>>> b1.authors.filter(name__exact='Carl')

[]

 

查看tom2有那些书

>>> tom2.book_set.all()

[<Book: Pyhon book1>]

 

tom2添加一本书

>>> tom2.book_set.create(name="java")

<Book: java>

>>> tom2.book_set.all()

[<Book: Pyhon book1>, <Book: java>]

 

查看都有那些书

>>> books = Book.objects.all()

>>> books

[<Book: Pyhon book1>, <Book: java>]

 

去掉一本书

>>> tom2.book_set.remove(books[0])

>>> tom2.book_set.all()

[<Book: java>]

posted @ 2015-03-30 21:53  VNX  阅读(373)  评论(0编辑  收藏  举报