Python 模型中的项目不单独计算
我正在开发一个博客应用程序,但我遇到了一个问题 models.pyPython 模型中的项目不单独计算,python,django,django-views,Python,Django,Django Views,我正在开发一个博客应用程序,但我遇到了一个问题 models.py class Album(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True) file = models.ImageField(upload_to='posts',null=True,blank=True) video = models.FileField(upload_to=
class Album(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,default='',null=True)
file = models.ImageField(upload_to='posts',null=True,blank=True)
video = models.FileField(upload_to='videos',null=True,blank=True)
views.py
def new_story(request):
file = Album.objects.filter(user=request.user)
context = {'file':file}
return render(request, 'mains/new_story.html', context)
当我使用
video\u limit=Album.objects.filter(user=request.user,video\u isnull=False)。count()
然后它也计算文件
对象,但我尝试只计算视频对象
我想做的事情:-
在相册
模型中有两个字段
,我正在尝试分别对文件和视频进行计数。当我在模板中使用{{file.count}}
计数时,它会对所有文件和视频进行计数,但当我尝试单独计数时,{file.video.count}
则不会显示
我不知道如何单独计数。{{{file.video.count}}
是空的,因为该文件是查询集,并且没有“video”属性
您可以实现您想要的,而无需使用聚合。最简单的方法是单独存储视频计数并将其传递到上下文:
def new_story(request):
file = Album.objects.filter(user=request.user)
video_count = file.filter(video__isnull=False).count()
context = {
'file': file,
'video_count': video_count
}
return render(request, 'mains/new_story.html', context)
在模板中,您可以使用{{video\u count}}
更新:
尝试用以下内容替换视频计数:
video_count = file.exclude(video='').count()
或
见Django一章docs@yedpodtrzitko,但我没有多个模型
。是的,你肯定应该读这一章。我以前已经读过了,但我没有找到聚合
,只有在模型上你应该会得到错误。。。由于文件
不包含视频
。。。这是一个查询集。。。没有一件东西…谢谢你的努力。但它仍然在计算文件
对象。我只是尝试计数视频对象
。当我添加文件(不是视频)并计数视频时,数字会增加扫描您尝试视频\u count=file.exclude(video='').count()
?
from django.db.models import Q
video_count = file.filter(Q(video__isnull=True) | ~Q(video='')).count()