iT邦幫忙

0

Django 取出外部鍵

想請問一下Django 在後台有建設了外部鍵
但我要怎麼在view下程式碼取出外部鍵的資料
我上網爬文很久但都看不太懂

1 個回答

0
froce
iT邦大師 2 級 ‧ 2019-04-01 00:34:39
最佳解答

看不太懂你的描述:
我用我想到的範例好了,2.0的版本。

models.py

class Author(models.Model):
    name = models.TextField()

class Book(models.Model):
    bookname = models.TextField()
    author = models.ForeignKey(
        Author
    )

urls.py

path("search_books_for_author/<str:author>/", search_books_for_author)
# 藉由網址得到查詢之作者

views.py

def search_books_for_author(request, author):
    author = Author.objects.get(name=author)
    all_books_for_author = Book.objects.filter(author=author)
    # 取得查詢之作者下的所有書籍

or

def search_books_for_author(request, author):
    author = Author.objects.get(name=author)
    all_books_for_author = author.book_set.all()
    # 取得查詢之作者下的所有書籍,使用「關係管理器」來取
    # Django的外鍵可以透過「小寫model名_set」來取代原本預設的「objects」關係管理器來存取

另一種方式,透過related_name來存取
models.py

class Author(models.Model):
    name = models.TextField()

class Book(models.Model):
    bookname = models.TextField()
    author = models.ForeignKey(
        Author,
        related_name = "books"
        # 在外鍵加入 related_name 參數
    )

views.py

def search_books_for_author(request, author):
    author = Author.objects.get(name=author)
    allbooksforauthor = author.books.all()
    # 取得查詢之作者下的所有書籍

我要發表回答

立即登入回答