###多表查詢 通常的多表查詢都是直接創建一個多對多關係django
class Books(models.Model): users = models.ManyToManyField(User, related_name='t_books', blank=True) name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
好比說上面的額代碼,這樣就會建立一個book和user的關聯表,可是有些複雜場景,關聯表中不單單有兩個表的主鍵, 還有一些其餘個性化屬性,這個時候就須要單獨寫一個class來聲明多對多關係,以下app
class Assets(models.Model): users = models.ForeignKey(User, related_name='t_assets', null=True, on_delete=models.CASCADE) books = models.ForeignKey(Policy, related_name='t_assets', on_delete=models.CASCADE) host = models.ForeignKey(Host, related_name='t_assets', null=True, on_delete=models.CASCADE) title=models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Books(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
這個時候列舉一些查詢場景code
一、根據books中的屬性來查詢用it
Books.objects.filter(name="aaa")
二、根據assets中的title來查詢books,這個時候就須要用到related_name屬性來查詢,而且須要使用雙下劃線class
Books.objects.filter(t_assets__title="aaa") #模糊查詢 Books.objects.filter(t_assets__title__icontains="aaa")
也能夠查詢assets而後反向查詢object
_books=list() aa=Assets.objects.filter(title="aaa").all() for a in aa: _books.append(a.books)
三、根據user類中的name查詢booksdate
Books.objects.filter(t_assets__users__name="aaa")
四、多字段模糊匹配,這個時候就須要用到django提供的Q類來封裝查詢語句 Books.objects.filter(Q(name__icontains=search) | Q(t_assets__title__icontains=search) | Q( t_assets__users__name__icontains=search))model