Django-ORM-查询API (连表查询)

有Book表——单表查询:

  查询Book表中所有的对象:Book.objects.all()            ————对象集合

  按条件过滤:Book.objects.filter(id=1)                        ————对象集合 

        Book.objects.get(id=1)           ————对象

  queryset.first()、queryset.last()得到的都是对象

———————————————————————————————————————————————————————————————————————————————

连表查询:

有Book (id, title, price,date, publish)、Publish (id, name, addr)、Author (id, name)三张表:

Book表和Publish表是一对多的关系,Book与Author表是多对多的关系。

class Publish(models.Model):
    name = models.CharField()
    addr = models.CharField()

class Author(models.Model):
    name = models.CharField()
    book = models.ManyToManyField('Book')

class Book(models.Model):
    title = models.CharField()
    price = models.IntegerField()
    date = models.DateField()
    publish = models.ForeignKey('Publish')

查询《百年孤独》的出版社:               Book.objects.filter(title='百年孤独').first().publish.name      ————正向查询

查询  魔幻出版社  出版过的所有书籍:book_list=Publish.objects.get(name='魔幻出版社').book_set.all()      ————反向查询(注意publish对象的book_set属性)

通过values & filter配合双下划线__来查询(*****):

先看一个简单的单表查询:查询《百年孤独》的价格:Book.objects.filter(title='百年孤独').values('price')        ————包含字典的集合对象:<QuerySet [{'price': Decimal('99.00')}]>

查询《百年孤独》的出版社(正向):Book.objects.filter(title='百年孤独').values('publish__name')             ———— <QuerySet [{'publish__name': '魔幻现实出版社'}]>

查询《百年孤独》的出版社(反向):Publish.objects.filter(book__title='百年孤独').values('name')         ————<QuerySet [{'name': '魔幻现实出版社'}]>

价格大于100的书籍的所有作者:

    1、Book.objects.filter(price__gt=100).values('authors__name')

    ————<QuerySet [{'authors__name': '陈冠希'}, {'authors__name': '兰陵笑笑生'}, {'authors__name': 'peterpan'}]>

    2、Author.objects.filter(book__price__gt=100).values('name')

    ————<QuerySet [{'name': '陈冠希'}, {'name': '兰陵笑笑生'}, {'name': 'peterpan'}]>

  

  

Life is short,i use python!
原文地址:https://www.cnblogs.com/chengnanlangzi/p/7461226.html