您的位置:首页 > 编程语言 > Python开发

django+python+操作数据库多表关联-增删改查-many-to-many-many-to-one

2014-03-18 15:58 288 查看
class Author(models.Model):

manytomany   

 name=models.CharField(max_length=10)

    age=models.IntegerField(max_length=5

    sex=models.CharField(max_length=4)

class Book(models.Model):

    title =models.CharField(max_length=20)

    authors=models.ManyToManyField(Author)

 author=Author()

    book=Book()

    author.name='zhangsan'

    author.age=12

    author.sex='男'

    book.title='三国演义'

    book.save()

    author.save()

    author1=Author()

    author1.name='lisi'

    author1.age=32

    author1.sex='女'

    author1.save()

    book.authors.add(author)

    book.authors.add(author1)

    Author.objects.create(name='wangwu',age=33,sex='女')

many-to-one

class Person (models.Model):

    name=models.CharField(max_length=10)

    age=models.IntegerField(max_length=5)

class Books(models.Model):

    person=models.ForeignKey(Person,related_name='person_book')

    #pubtime=models.DateField()

    title=models.CharField(max_length=15)

def index(req):

   print '222'

   person1 =Person()

   person1.age=12

   person1.name='李四'

   person1.save()

   book1=Books()

   book1.title='三国演义'

   book1.person=person1

   book1.save()

   book2=Books()

   book2.title='三国演义'

   book2.person=person1

   book2.save()

取出对象:

b = Book.objects.get(id=50)  

b.authors.all()  

b.authors.filter(first_name='Adam') 
从作者出发获取书籍

a = Author.objects.get(id=1)  

a.book_set.all()  

删除对象

a = Author.objects.get(id=1)

b = Book.objects.get(id=50)

b.authors.remove(a) 或者 b.authors.filter(id=1).delete()

 



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: