3 回答

TA貢獻1802條經驗 獲得超5個贊
您不必為此重寫方法 [Django-doc],因為該對象已經傳遞到上下文.get_queryset(…)
。您可以簡單地在模板中渲染它:
{{ object.content }}
如果您確實在上下文中需要它,您可以將其實現為:
class PostDetailView(DetailView):
? ? model = Post
? ??
? ? # …
? ??
? ? def get_context_data(self, **kwargs):
? ? ? ? context = super().get_context_data(**kwargs)
? ? ? ? context.update(
? ? ? ? ? ? texts=self.object.content
? ? ? ? )
? ? ? ? return context
如果您需要所有帖子對象,您可以將它們添加到上下文中:
class PostDetailView(DetailView):
? ? model = Post
? ??
? ? # …
? ??
? ? def get_context_data(self, **kwargs):
? ? ? ? context = super().get_context_data(**kwargs)
? ? ? ? context.update(
? ? ? ? ? ? texts=self.object.content,
? ? ? ? ? ? posts=Post.objects.all()
? ? ? ? )
? ? ? ? return context
并將它們呈現為:
{% for post in posts %}
? ? {{ post.content }}
{% endfor %}
在增加視圖計數器以避免競爭條件時,最好使用表達式F
[Django-doc]:
class PostDetailView(DetailView): model = Post def get_object(self): obj = super().get_object() 視圖 = obj.view_count obj.view_count =?F('view_count') + 1?obj.save() obj.view_count =視圖+1?返回 obj

TA貢獻1856條經驗 獲得超5個贊
只需查詢所有對象并循環查詢集即可根據您的需要操作它們,如下所示:
def your_view(self, **kwargs):
# Get all table entries of Model Post
queryset = Post.objects.all()
# Loop each object in the queryset
for object in queryset:
# Do some logic
print(object.content)
[...]
return (..., ...)

TA貢獻1942條經驗 獲得超3個贊
首批進口車型
from . models import Post
然后在你的函數中
data=Post.objects.values('content').all()
現在 data 具有內容字段 data=[{'content':first_value},{'content':second_value},..like this...] 中的所有值
添加回答
舉報