zoukankan      html  css  js  c++  java
  • ORM数据库查询操作之基于双下划线的跨表查询

     创建表结构

    from django.db import models
    
    
    class Book(models.Model):
        title=models.CharField(max_length=32)
        publishDate=models.DateField()
        price=models.DecimalField(max_digits=5,decimal_places=2)
    
        # 出版社可以发布多部书(一对多)
        publish=models.ForeignKey('Publish')
    
    
        # 一个人可以写多本书,一本书也可以由多个人撰写(多对多)
        authorList=models.ManyToManyField('Author')
    
    class Author(models.Model):
        name=models.CharField(max_length=32)
        age=models.IntegerField()
        addr=models.CharField(max_length=32)
        tel=models.CharField(max_length=13)
    
    class Publish(models.Model):
        name=models.CharField(max_length=32)
        addr=models.CharField(max_length=32)
    

    2 urls配置

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    
    urlpatterns = [
        url(r'^index/', views.index),
    ]
    

    5 测试数据

    作者数据

    出版社数据

    书籍数据

    4 编写views代码 

    def index(request):
        bookobj = models.Book.objects.all()
        # 练习1:  查询人民出版社出版过的所有书籍的名字与价格(一对多)
        # ret = models.Book.objects.filter(publish__name='山西出版社').values_list('title')
        # ret = models.Publish.objects.filter(name='山西出版社').values_list('book__title','book__authorList__name')
        # ret = models.Author.objects.filter(book__publish__name='山西出版社').values_list('book__title')
        # 练习2: 查询egon出过的所有书籍的名字(多对多)
        # ret = models.Book.objects.filter(authorList__name='alex').values_list('title')
        # ret =models.Author.objects.filter(name='alex').values_list('book__title')
        # 练习3: 查询人民出版社出版过的所有书籍的名字以及作者的姓名
        # ret = models.Publish.objects.filter(name='机械先驱出版社').values_list('book__title','book__authorList__name')
        # ret = models.Book.objects.filter(publish__name='机械先驱出版社').values_list('title','authorList__name')
        # ret = models.Author.objects.filter(book__publish__name='机械先驱出版社').values_list('book__title','name')
        # 练习4: 手机号以151开头的作者出版过的所有书籍名称以及出版社名称
        # ret = models.Author.objects.filter(tel__startswith='158').values_list('book__title','book__publish__name')
        # ret =models.Publish.objects.filter(book__authorList__tel__startswith='158').values_list('book__title','name')
        # ret = models.Book.objects.filter(authorList__tel__startswith='158').values_list('publish__name','title')
        # print(ret)
     	return HttpResponse('OK')
    

      

  • 相关阅读:
    sql server 中 bit 字段的 查询方法
    C# 4.0新特性"协变"与"逆变"以及背后的编程思想
    marginleft是做边距,是宽度 left是定位盒子左上角左边位置的一个点
    什么是企业库 怎么使用企业库 企业库的好处 企业库的目标
    SQL各种Join用法(Full,Left,Out,Inner)
    JavaScript计算两个文本框内数据的乘积(四舍五入保留两位小数)
    SQL VIEW(视图)
    Sql ISNULL() 函数
    left join 和 left outer join 有什么区别
    18个不常见的C#关键字,您使用过几个?
  • 原文地址:https://www.cnblogs.com/supery007/p/7756146.html
Copyright © 2011-2022 走看看