1、vim blog/models.py
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.ManyToMany(Author)
def unicode(self):
return self.name
2、python manage.py syncdb
sqlite3 cs.db
.tables;
3、python manage.py shell
from blog.models import Author,Book
Author.objects.create(name='a1')
Author.objects.create(name='a2')
authors = Author.objects.all()
>>> authors
[<Author: a1>, <Author: a2>]
>>> b1 = Book()
>>> b1.name='book1'
>>> b1.save()
>>> b1
<Book: book1>
a1 = Author.objects.get(name__exact='a1')
b1.authors.add(a1)
b1.authors.all()
b1.authors.remove(a1)
b1.authors.all()
b1.authors.filter(name__exact='a1') 做一个过滤
a1.book_set.add(b1)
a1.book_set.create(name='book2')
a1.book_set.all()
books = Book.objects.all()
books
a1.book_set.remove(books[0]) 0是下标,表示把第一个删除
a1.book_set.all()