我的目标:每月获取显示在模板中的项目数,例如:2021-5,2021-10,9月2021-3,2021-2,等等。
我所做的。我首先创建了一个测试项目和从CreateView继承的索引视图(表单需要它)。一切都很好。然而,在我的主要项目中,我的IndexView是从django的TemplateView继承而来的,它用相同的代码显示如下:9月份2021 - 1,9 2021 - 1,10 2021 - 1,10 2021 - 1,10 2021 -1.你说对了。因此,出于某种原因,它将每一项视为一个单独的日期,而不试图对其进行汇总。
因此,差异制造者必须是来自django中不同视图的继承,然而,在我的主要项目中,我不能让我的索引视图继承CreateView。而且,我对Django还是新手,我很感激我能得到的一切帮助。我花了很大力气才弄明白这一点。
下面是我的工作代码(在测试项目中):
models.py
class Movie(models.Model):
title = models.CharField('Movie name', max_length=100)
gross = models.IntegerField('Gross', help_text='Worldwide, in dollars.')
release_date = models.DateField('Date of release', blank=True, null=True)
def __str__(self):
return self.titleviews.py (注意上下文的“每月”行)
class IndexView(CreateView):
form_class = CreateMovieForm
template_name = 'home/index.html'
success_url = '/'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# per_month = queryset of dictionaries: month + number of movies in each month
context['per_month'] = Movie.objects.annotate(
month=TruncMonth('release_date')).values('month').annotate(c=Count('id')).values('month', 'c')
context['movies'] = Movie.objects.all()
return contextforms.py (不确定这里是否相关,只是以防万一)
class CreateMovieForm(forms.ModelForm):
class Meta:
model = Movie
fields = '__all__'
widgets = {'release_date': DateInput(attrs={'value': timezone.now().date})}index.html
{% for month in per_month %}
<ul>
<li>
{{ month.month|date:"M Y" }} - {{ month.c }}
</li>
</ul>
{% endfor %}输出:
2021年8月-2日9月2021年10月1日2021 -3日
下面是我的不工作的代码(主要项目):
models.py
class Item(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(User, on_delete=models.CASCADE)
assigned_to = models.ManyToManyField(User)
date_posted = models.DateTimeField(auto_now_add=True)
deadline_date = models.DateField(null=True)注意:我尝试了两种方法: date_posted和deadline_date (万一问题是DatetimeField,而不是DateField),但没有帮助。
views.py (相同上下文的“每月”行)
class IndexView(LoginRequiredMixin, TemplateView):
template_name = 'bugtracker/main.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# per_month = queryset of dictionaries: month + number of movies in each month
context['per_month'] = Item.objects.annotate(
month=TruncMonth('date_posted')).values('month').annotate(c=Count('id')).values('month', 'c')index.html (与上文相同)
输出:
2021年8月1日2021年10月1日2021年10月1日
发布于 2021-10-12 20:43:33
您应该添加一个.order_by(…)来强制分组,因此:
context['per_month'] = Item.objects.values(
month=TruncMonth('date_posted')
).annotate(c=Count('id')).order_by('month')https://stackoverflow.com/questions/69546759
复制相似问题