如何使用created_at过滤和更新Django模型

thtygnil  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(141)

我有两个模特

class Records(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    Approved = models.BooleanField(default=False)
    Date = models.DateTimeField(default=datetime.now, blank=True)
    
class Request(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    Approved = models.BooleanField(default=False)
    Date = models.DateTimeField(default=datetime.now, blank=True)

如果Request中的ApprovedTrue,我希望cron每1分钟更新一次Record
我试过这个...

def user_request():
    if Request.objects.exists():
        check=Request.objects.get()
        with transaction.atomic():
            if check.Approved == True:
                Records.objects.filter(user=check.user, Date=check.Date).update(Approved=True)
                Request.objects.get().delete()

我不明白为什么当这两个模型对象同时创建时,这个逻辑不起作用,甚至当我确认日期时间时,日期、分钟和秒都是相同的。

ifmq2ha2

ifmq2ha21#

您需要指定要更新的Request

def user_request(req):
        req_id = req.id
        with transaction.atomic():
            if req.Approved:
                record = Records.objects.filter(user=check.user)
                record.update(Approved=True)
                req.delete()
        return req_id

需要对每个请求对象运行方法user_request
CRON作业示例:

from datetime import datetime
...

today_requests = Request.objects.filter(Date=datetime.today())
updated_requests = [user_request(req) for req in today_requests]

相关问题