我在Django模型中有两个TimeField,我想在另一个数据库字段,函数或类或任何最佳实践中计算持续时间。
我以后想使用此信息来显示按“ prosjekt”和“ aktivitet”排序的信息。例如:
Prosjekt1 aktivitet1 = 4 hours aktivitet2 = 2,5 hours aktivitet3 = 1 hour Prosjekt2 aktivitet1 = 5,5 hours aktivitet3 = 0,5 hours Prosjekt3 aktivitet3 = 8,5 hours etc.
这是我的模特
from django.db import models
from django.contrib.auth.models import User
from prosjektregister.models import Prosjekt
class Aktivitet(models.Model):
aktivitet = models.CharField(max_length=100)
def __str__(self):
return self.aktivitet
class Tid(models.Model):
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
prosjekt = models.ForeignKey(Prosjekt, on_delete=models.CASCADE)
dato = models.DateField()
tid_fra = models.TimeField()
tid_til = models.TimeField()
aktivitet = models.ForeignKey(Aktivitet, on_delete=models.SET_NULL, null=True)
def publish(self):
self.save()
我的观点:
@login_required
def reg_tid(request):
if request.method == 'POST':
form = TidForm(request.POST, user=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect('/tid/tidsregister/')
else:
form = TidForm(user=request.user)
return render(request, 'tid/tid.html', {'form': form})
@method_decorator(login_required, name='dispatch')
class TidsRegister(ListView):
model = Tid
template_name = 'tid/tidsregister.html'
context_object_name = 'tidsregister'
def get_queryset(self):
return Tid.objects.filter(author=self.request.user)
@login_required
def tid_edit(request, pk):
post = get_object_or_404(Tid, pk=pk)
if request.method == 'POST':
form = TidForm(request.POST, instance=post, user=request.user)
if form.is_valid():
post = form.save()
return HttpResponseRedirect('/tid/tidsregister/')
else:
form = TidForm(instance=post, user=request.user)
return render(request, 'tid/tid.html', {'form': form})
答案 0 :(得分:0)
我将尝试提供完整的示例,我想您可以从这里找出答案:
class Activity(models.Model):
title = models.CharField(
max_length=255,
verbose_name="Title",
)
def __str__(self):
return self.title
class Period(models.Model):
activity = models.ForeignKey(
to=Activity,
on_delete=models.CASCADE,
related_name="periods"
verbose_name="Activity",
)
title = models.CharField(
max_length=255,
verbose_name="Title",
)
start_at = models.DateTimeField(
verbose_name="Start at",
)
end_at = models.DateTimeField(
verbose_name="End at",
)
def __str__(self):
return "Period"
activities = Activity.objects.all()
for activity in Activity.objects.all():
print(f"Activity: {activity.title}")
print("Periods:")
for period in activity.periods.all():
print(f"{period.title} - {period.end_at - period.start_at}") # (period.end_at - period.start_at) is a timedelta object, you can get (period.end_at - period.start_at).total_seconds() for example