我在Django上做应用,只是学习,确切地说,我有一个问题,我做的列表,其中有一个目标,每个目标都有实现这一目标的步骤,可以有无限数量。好吧,我需要计算目标和显示的百分比,即进行计数kollichesvo(已经实施)并除以阶段的总和。这是问题所在。
型号:
class Post(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Stage(models.Model):
keys = models.ForeignKey(Post)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField()
end = models.BooleanField(default=False)
procent = models.IntegerField(default=0)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
视图
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
posts = Stage.objects.filter(keys__exact=pk,)
return render(request, 'blog/post_detail.html', {'post': post, 'posts': posts})
此示例
x = len(posts)
for m in posts:
if end == True:
ar = ar + 1
stages = (ar / x * 100)
答案 0 :(得分:0)
向您的班级添加方法:
class Post(models.Model):
# ...
def percentage_complete(self):
total = self.stage_set.count()
completed = self.stage_set.filter(end=True).count()
return (float(completed) / total) * 100
在您的模板中,假设您有一个post
上下文变量:
% done: {{ post.percentage_complete }}