zoukankan      html  css  js  c++  java
  • ORM跨表查询问题

    环境准备:

    表结构

    from django.db import models
    
    # Create your models here.
    class Publisher(models.Model):
        id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=32)
    
    
    class Book(models.Model):
        id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=32)
    
        publisher = models.ForeignKey('Publisher', related_name='person_book', related_query_name='ooxx')

    表数据

    # Book表
    id   title  pubtime          person_id
    1    书1    1533225600000    1
    2    书2    1533225600000    1
    3    书3    1534435200000    1
    4    书4    1535644800000    2
    5    书5    1535126400000    2
    id   name    
    1    出版社1    
    2    出版社2    
    3    出版社3    

    执行过程:

    当反向查询的时候,通过Publisher表查询Book表数据。

    publishers = Publisher.objects.all()  # 获取说有的出版社对象
    for publisher in publishers:  # 循环每一个出版社
    p_id = publisher.id # 取到这个出版社的id
    books = Book.objects.filter(publishet_id=p_id).all() # 取到这个出版社出版的所有书籍
    print(books[0].id) # 打印第一本书的id

    异常情况:

    list index out of range  提示index超出范围。

    当p_id=3的时候,查询不到对象,就不会报错。

    结束!

  • 相关阅读:
    python基础
    python中自定义的栈
    python内置函数
    python函数之可迭代对象、迭代器的判断
    关系型数据库
    数据库基础知识
    进程间通信--管道
    共享内存应用范例
    Win7秘籍 如何用压缩卷调整不合理分区
    KL-divergence
  • 原文地址:https://www.cnblogs.com/aaronthon/p/9732237.html
Copyright © 2011-2022 走看看