Cal*_*Mac 5 mysql django post django-templates django-models
我有一个问题,我有一个 MariaDB 事件与我的 Django 模型相结合。对于上下文,这是我的模型代码:
class PartGroup(models.Model):
GroupID = models.AutoField(primary_key=True, unique=True)
Label = models.CharField(max_length=40, blank=True)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE, null=True)
InspectionPeriod = models.IntegerField(blank=False, null=True)
LastInspected = models.DateField(blank=True, null=True)
InspectionDue = models.CharField(max_length=255, blank=True)
ConnectedTo = models.ManyToManyField('self', blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)
我想在这里强调的领域是InspectionPeriod,LastInspected和InspectionDue。我有另一个模型,它添加了与GroupID. 这包含检查日期:
class GroupInspection(models.Model):
InspectionID = models.AutoField(primary_key=True, unique=True)
GroupID = models.ForeignKey('PartGroup', on_delete=models.CASCADE, null=True, unique=True)
class GroupReport(models.Model):
ReportID = models.AutoField(primary_key=True, unique=True)
InspectionID = models.ForeignKey('GroupInspection', on_delete=models.CASCADE, null=True)
Date = models.DateField(auto_now=False, auto_now_add=False, null=True)
Comment = models.CharField(max_length=255, blank=True)
Signature = models.CharField(max_length=255, blank=True)
Run Code Online (Sandbox Code Playgroud)
我有一个 MariaDB 事件来更新该LastInspected字段,然后我视图中的一些代码会根据检查期间检查该日期,以查看检查是否到期。
这就是问题发生的地方
我必须每 1 秒更新一次我的 MariaDB 事件,以使这项工作相当顺利。我不确定这是否是绝对可怕的性能明智,如果有人有另一种更流畅的解决方案,那是受欢迎的。但这不是真正的问题。当我创建检查时,这会立即重定向到我的组模板页面。这需要不到一秒钟的时间来重定向,这让我的用户感到困惑,因为他们刚刚创建了一个检查并且它不会显示在重定向中,除非他们在 1 秒后立即刷新。
我怎样才能解决这个问题?
编辑 1 我忘了提到 - 这在模板级别的工作方式是我有一个页面显示我的所有组及其属性的表格视图。然后我有几个按钮可以根据按下的按钮创建检查。这只是重定向回同一页面,这就是为什么一秒钟的事情是一个问题,因为重定向通常需要不到一秒钟。
编辑 2这是我的观点:
def groupList(request, site):
status = "default"
if request.method == "POST":
list = GroupInspection.objects.filter(GroupID = request.POST.get("group"))
if not list.exists():
insp = GroupInspection.create(PartGroup.objects.get(GroupID = request.POST.get("group")))
insp.save()
if 'pass' in request.POST:
groupReport = GroupReport.create(GroupInspection.objects.get(GroupID = request.POST.get("group")), date.today(), "Pass", request.user.username)
groupReport.save()
if 'fail' in request.POST:
groupReport = GroupReport.create(GroupInspection.objects.get(GroupID = request.POST.get("group")), date.today(), "Fail", request.user.username)
groupReport.save()
if 'checkSubmit' in request.POST:
groupReport = GroupReport.create(GroupInspection.objects.get(GroupID = request.POST.get("group")), date.today(), request.POST.get("comments"), request.user.username)
groupReport.save()
status = "changed"
siteselected = Site.objects.get(SiteID = site)
groupList = PartGroup.objects.filter(SiteID = siteselected)
warnings = 0
expired = 0
good = 0
for group in groupList:
if group.LastInspected == None:
group.InspectionDue = "Yes"
expired = expired + 1
else:
Deadline = group.LastInspected + timedelta(days=group.InspectionPeriod)
if datetime.now().date() > Deadline:
group.InspectionDue = "Yes"
expired = expired + 1
elif datetime.now().date() > (Deadline - timedelta(days=30)):
group.InspectionDue = "<30 Days"
warnings = warnings + 1
else:
group.InspectionDue = "No"
good = good + 1
group.save()
context = {
'status': status,
'SiteNo': siteselected.SiteID,
'SiteName':siteselected.SiteName,
'groupList': groupList,
'expired': expired,
'warnings': warnings,
'good': good,
}
template = loader.get_template('moorings/groupList.html')
return HttpResponse(template.render(context, request))
Run Code Online (Sandbox Code Playgroud)
编辑 3这是我的 SQL 事件
CREATE EVENT updateLastInspected
ON SCHEDULE EVERY 1 SECOND
DO
UPDATE proj_partgroup g INNER JOIN ( SELECT i.GroupID_id, max(r.Date) Date FROM proj_groupinspection i INNER JOIN proj_groupreport r ON r.InspectionID_id = i.InspectionID GROUP BY i.GroupID_id ) t ON g.GroupID = t.GroupID_id SET g.LastInspected = t.Date;
Run Code Online (Sandbox Code Playgroud)
您可以将 SQL 事件替换为在任何更新后运行的Django 信号GroupReport,并且如果创建了新报告 - 则更新对应的PartGroup上次更新日期。
项目/signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.apps import apps
GroupReport = apps.get_model("proj", "GroupReport")
PartGroup = apps.get_model("proj", "PartGroup")
@receiver(post_save, sender=GroupReport)
def update_partgroup_lastinspection(sender, instance, created, **kwargs):
if created:
# cause FKs can be null - may need to add
# null checks or try / except
pg = instance.InspectionID.GroupID
if instance.Date > pg.LastInspected:
pg.LastInspected = instance.Date
pg.save(update_fields=['Date'])
# another option to perform same update
PartGroup.objects.filter(
LastInspected__lt=instance.Date,
group_inspection__group_report=instance
).update(
LastInspected=instance.Date
)
Run Code Online (Sandbox Code Playgroud)
项目/apps.py
...
class ProjConfig(AppConfig):
name = "proj"
...
def ready(self):
import proj.signals
Run Code Online (Sandbox Code Playgroud)
您可以跳过检查该值是否更大并立即更新。或者在模型的save()方法中添加逻辑(通常比信号更受欢迎)。
先前的答案 - 此处情况并非如此,groupList 包含对实例的更改。
您正在返回groupList包含旧结果的内容。
这样做的原因是,在迭代 ( for group in groupList) QuerySet 时,会使用缓存在该 QuerySet 实例中的结果来评估,并且稍后在上下文中使用它时 - 尽管实例已在数据库中更新,但该评估结果会被传递。需要运行并再次评估查询集才能获取新结果。
重用 QuerySet 并再次评估它的一个简单解决方案- 是将.all()附加到前一个 QuerySet - 这将制作所提供的 QuerySet 的副本,并且由于它是新的 - 它尚未评估。
context = {
...
'groupList': groupList.all(),
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |