2 回答

TA貢獻(xiàn)1909條經(jīng)驗 獲得超7個贊
在類級別,created_on是 a DateTimeField,而不是datetime對象(不是類)所擁有的Post 對象。如果你想添加一個格式化它的屬性,你可以使用:
class Post(models.Model):
# …
created_on = models.DateTimeField(auto_now_add=True)
@property
def publishdate(self):
return self.created_on.strftime('%Y/%m')
# …
話雖如此,格式化數(shù)據(jù)通常不是模型的任務(wù)。模型用于存儲和表示數(shù)據(jù)。例如,在模板中,您可以使用|date模板標(biāo)簽 [Django-doc]以datetime指定格式格式化對象。對于給定的Post對象post,您可以將其格式化為:
{{ post.created_on|date:'Y/m' }}
對于 URL,您可以使用兩個參數(shù):
urlpatterns = [
path('', views.PostList.as_view(), name='home'),
path(
'<int:year>/<int:month>/<slug:slug>',
views.PostDetail.as_view(),
name='post_detail'
)
]
在您看來,您可以使用以下內(nèi)容進(jìn)行過濾:
class PostDetail(DetailView):
model = Post
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).filter(
created_on__year=self.kwargs['year'],
created_on__month=self.kwargs['month']
)
在模板中,您可以使用以下對象鏈接到視圖post:
{% url 'post_detail' post.created_on.year post.created_on.month post.slug %}

TA貢獻(xiàn)1802條經(jīng)驗 獲得超6個贊
難道不應(yīng)該通過self
在類級別向?qū)傩蕴砑?a 來工作嗎?
publishdate = self.created_on.strftime('%Y/%m')
添加回答
舉報