连续跨表的弊端(对检索的数据要在关联的表中都要有关系)
1.book表与author表的关系表:

2.book表:

3.author表:

4.authordetail表:

#所有表的关系:
from django.db import models
# Create your models here.
class Author(models.Model): #比较常用的信息放到这个表里面
    nid = models.AutoField(primary_key=True)
    name=models.CharField( max_length=32)
    age=models.IntegerField()
    ad = models.OneToOneField(to="AuthorDetail", to_field="nid", on_delete=models.CASCADE)#OneToOneField()实现了一对一的关联,to='AuthorDetail'关联的表,to_field='nid'关联的属性
class AuthorDetail(models.Model):#不常用的放到这个表里面
    nid = models.AutoField(primary_key=True)
    birthday=models.DateField()
    telephone=models.BigIntegerField()
    addr=models.CharField( max_length=64)
    def __str__(self):
        return str(self.birthday)
class Publish(models.Model):
    nid = models.AutoField(primary_key=True)
    name=models.CharField( max_length=32)
    city=models.CharField( max_length=32)
    email=models.EmailField()
class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField( max_length=32)
    publishDate=models.DateField()
    price=models.DecimalField(max_digits=5,decimal_places=2)
    publishs = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE)
    authors = models.ManyToManyField(to='Author', )
下面我们通过django orm连续跨表进行检索:
这个是通过authordetail表直接检索author表的信息:
obj = models.AuthorDetail.objects.filter(telephone__gt=777).values('author__name')
   print(obj)
检索结果:
< QuerySet[{'author__name': '桔梗'}, {'author__name': '镰鼬'}] >
如果运用连续跨表,并且book_authors 表中并没有桔梗这个作者出版的书籍:
obj = models.Book.objects.filter(authors__ad__telephone__gt=777).values('authors__name')
    print(obj)
检索结果:
<QuerySet [{'authors__name': '镰鼬'}]>
注意:连续跨表需要对每个表都有关系的表信息才能检索出来,就像桔梗没有在book_author表中出现 ,就无法从book中检索出来。

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号