Django学习笔记一十三——ORM查询练习

前面基本上已经讲了ORM常用的使用方法,这里结合实例做一些查询联系

数据结构

 这里我们把前面用到的各种关系都加上,做一个下面样的数据库

 

class Book(models.Model):
    title = models.CharField(max_length=32)
    publish_date = models.DateField(auto_now_add=True)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    memo = models.TextField(null=True)
    # 创建外键,关联publish
    publisher = models.ForeignKey(to="Publisher",on_delete=models.CASCADE)
    # 创建多对多关联author
    author = models.ManyToManyField(to="Author")

    def __str__(self):
        return self.title

# 出版社
class Publisher(models.Model):
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)

    def __str__(self):
        return self.name

# 作者
class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    phone = models.CharField(max_length=11)
    detail = models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE)

    def __str__(self):
        return self.name

# 作者详情
class AuthorDetail(models.Model):
    addr = models.CharField(max_length=64)
    email = models.EmailField()

 

查询数据

 1.查找所有书名里包含Python的书

book = models.Book.objects.filter(title__contains='Python'

2.查找所有2019年出版的书

book = models.Book.objects.filter(title__contains='Python')

3.查找价格大于10元的书

book = models.Book.objects.filter(price__gt=10)

4.查找在北京的出版社

publishers = models.Publisher.objects.filter(city='北京')

5.所有数据按照价格倒序排列

ret = models.Book.objects.all().order_by('-price')

6.查找“学习Python"书籍是在哪个城市出版的(跨表查询)

city = models.Book.objects.filter(title='学习Python').values('publisher__city')

7.查找”学习Python"书籍作者的地址(跨多表)

addr = models.Book.objects.filter(title = '学习Python').values('author__detail__addr')#跨了两张表

 

posted @ 2020-04-24 20:29  银色的音色  阅读(247)  评论(0编辑  收藏  举报