The title alone seems to be vague.
(仅标题似乎是模糊的。)
Here is the detail. (这是细节。)
I have the following Model:
(我有以下模型:)
class Post(models.Model):
title = models.CharField(max_length=100)
# deleted for brevity
created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
count_visits = models.PositiveIntegerField(default=1) # counts visit time of posts
and added the following code in blogs.html
:
(并在blogs.html
添加了以下代码:)
{% if post.created_at == post.updated_at %}
Posted {{ post.created_at|naturaltime }}
{% else %}
Updated {{ post.updated_at|naturaltime }}
{% endif %}
then I made a simple if statement
in DetailView
to keep track of number of visitors of a certain post:
(然后我在DetailView
做了一个简单的if statement
来跟踪某个帖子的访问者数量:)
def post_detail(request, title_slug):
obj = get_object_or_404(Post, slug=title_slug)
session_key = f'key_{title_slug}'
if not request.session.get(session_key, False):
obj.count_visits += 1
obj.save()
request.session[session_key] = True
return render(request, 'blogApp/detail.html', {'post': obj})
Here is the problem, When I create a post, in list view it shows Posted now
.
(这是问题所在,当我创建帖子时,在列表视图中显示“立即Posted now
。)
but as I click the post to view its detail.
(但是当我单击该帖子以查看其详细信息时。)
It shows Updated now
(它显示立即Updated now
)
and I think I know what is the problem, when I go to detail view.
(当我进入详细视图时,我想我知道出了什么问题。)
it creates a session_key
, increments obj.count_visits += 1
and save the object obj.save()
. (它创建一个session_key
,使obj.count_visits += 1
递增并保存对象obj.save()
。)
When obj.save()
is called it updates the database including updated_at
field and that is why I get Updated now
.
(调用obj.save()
,它将更新数据库,其中包括updated_at
字段,这就是为什么我Updated now
要Updated now
。)
How do I solve this?
(我该如何解决?)
I want to increment number of count_views
field, but when object is saved it shouldn't change updated_at
field. (我想增加count_views
字段的数量,但是保存对象时不应更改updated_at
字段。)
I hope you help me.
(我希望你能帮助我。)
Thank You (谢谢)
ask by Basir Payenda translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…