![](/img/trans.png)
[英]using datetime.utcnow() with DjangoTables2 render_FOO
[英]How to Pass Back Slug to Render_Foo In Django?
如何使用 django-tables2 通過render_foo將 slug 傳回?
models.py
class Library(models.Model):
name = models.CharField(max_length=128)
library_slug = models.SlugField(unique=True)
class Author(models.Model):
library = models.ForeignKey(Library)
author_slug models.Slugfield(unqiue=True)
class Book(models.Model):
author = models.ForeignKey(Author)
book_slug = models.SlugField(unique=True)
views.py
def LibraryTableView(request):
queryset = books.objects.values('author','book').annotate(book_count=Count('book'))
table = LibraryTable(queryset)
def AuthorTableView(request, author_slug):
queryset = books.objects.filter(book__author__author_slug=author_slug)
table = AuthorTable(queryset)
tables.py
class LibraryTable(tables.Table):
class Meta:
model = Book
fields = ('author', 'book_count')
def render_book_count(self, value, author_slug):
return format_html('<a href="{}">{}</a>', author_slug, value)
圖書館表 | 作者| 書數 | |--------|------------| | JK羅琳| 6 | | 布蘭登·桑德森| 12 | | 赫爾曼梅爾維爾 | 5 |
單擊作者 Herman Melville 時,它將深入到他的書
標題 | 類型 |
---|---|
類型 | 非虛構 |
奧莫 | 虛構 |
雷德伯恩 | 虛構 |
白鯨 | 虛構 |
提摩隆 | 詩歌 |
注意:如果我嘗試author = tables.Column(linkify=True)
,我會收到for linkify=True, Herman Mellville must have a method get_absolute_url
從表面上看,最簡單的方法是使用 linkify 並添加一個 get_absolute_url 方法。
class Author(models.Model):
library = models.ForeignKey(Library)
author_slug models.Slugfield(unqiue=True)
def get_absolute_url(self):
"""Returns a permalink for the author"""
return reverse(
"AuthorTableView",
kwargs={"author_slug": self.slug},
)
以這種方式設置的好處是,如果您更改 URL 結構,它將自動更新。 如果您進行了這樣的更改,硬編碼您的 HTML 格式 href 將會中斷。
盡管如此,如果您確實想對其進行硬編碼,那么您需要確保硬編碼的 URL 最終與您的 url 文件對 AuthorTableView 的期望相同。 例如,如果你的 url 文件有'/author/<str:slug>'
那么你會想要
def render_book_count(self, value, record):
return format_html('<a href="/author/{}">{}</a>', record.slug, value)
這里的重要區別是“value”是 book_count 列的列值,而 record 是整行,您可以使用“record.txt”查詢模型的其他部分。 財產'。
評論后更新:
此外,您不需要在 LibraryTableView 中使用“值”。 嘗試:
queryset = Author.objects.annotate(book_count=Count('book'))
這將使您的作者保持為具有 get_absolute_url() 方法的對象。 您將需要適當地更新您的 LibraryTable 類 Meta: 因為它實際上是您正在使用的作者模型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.