簡體   English   中英

如何使用 Django 中的查詢集更改日期時間字段

[英]How to change Datetime field with queryset in Django

這是 class

class Post(models.Model):
    author = models.ForeignKey(User)
    .
    .
    last_seen = models.DateTimeField(auto_add = True)

我想將 last_seen 時間更改為將來的另一個時間

last_seen = Post.objects.get(author = user).last_seen
if request.user.is_authenticated:
    last_seen = timezone.now()

當我運行 print(last_seen) 我發現它沒有改變並且仍然是舊的日期時間值有什么問題?

您沒有為帖子更新此內容,您只是將一個局部變量設置為當前時間戳。

您可以通過以下方式更新經過身份驗證的用戶的Post記錄:

from django.utils.timezone import now

if request.user.is_authenticated:
    Post.objects.filter(author=user).update(last_seen=now())

您尚未保存 object 更新后。 因此沒有反映。 你可以這樣做

your_post = Post.objects.get(author = user)
if request.user.is_authenticated:
    your_post.last_seen = timezone.now()
    your_post.update() // can also you object.save()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM