zoukankan      html  css  js  c++  java
  • 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')#跨了两张表
  • 相关阅读:
    前端H5
    nginx的location的匹配规则
    非旺玖原装的PL2303,请联系您的供货商
    Arduino 怎样添加第三方拓展
    Arduino的shiftOut函数作用
    arduino 的analogRead() 和analogWrite()
    composer安装TP的时候:错误提示:zsh: no matches found: 5.1.*
    Bootstrap3 模态框点击无效
    人人商城支付成功后在哪修改订单状态
    人人商城怎样判断订单是否支付
  • 原文地址:https://www.cnblogs.com/yinsedeyinse/p/12728726.html
Copyright © 2011-2022 走看看