1. 程式人生 > 其它 >Django多表連線查詢

Django多表連線查詢

1、一對一查詢

    models.OneToOneField(Entry)
    兩個實體類:Author , Wife
        1、通過 Author 找 Wife
            author = Author.objects.get(id=1)
            wife = author.wife
        2、通過 Wife 找 Author
            wife = Wife.objects.get(id=2)
            author = wife.author

2、一對多/多對一查詢

    model = models.ForeignKey(Entry)
    兩個實體類:Publisher(一) , Book(多)
    正向查詢:
        book 
= Book.objects.get(id=1) publisher = book.publisher 反向查詢 publisher = Publisher.objects.get(id=4) books = publisher.book_set.all()

3、多對多查詢

    1、什麼是多對多
        A表中的一條記錄可以與B表中的任意多條記錄匹配,同時B表中的每一條記錄也可以與A表中的任意多條記錄相匹配
    2、語法
        entry = models.ManyToManyField(Entry)
    
3、查詢 class Author(models.Model): ... ... publish = models.ManyToManyField(Publish) 正向查詢:在 Author 中查詢 Publish author = Author.objects.get(id=3) pub_list=author.publish.all() 通過關聯屬性.all() 反向查詢:在 Publisher 中查詢 Author pub
= Publisher.objects.get(id=1) auList = pub.author_set.all()