django - 即使为零也获取记录数
问题描述
我的脚本中有以下查询,它返回每个源名称今天添加的记录数。我添加了一个过滤器created_at__gte=today
。使用此信息,我正在创建一个表。现在的问题是,如果没有任何特定源名称的媒体记录,它就不会出现在输出中。我也希望它出现计数为零。你能指导我如何实现这一目标吗?
media_queryset = Media.objects.filter(
created_at__gte=today
).values('source__name').annotate(
total=Count('id'), last_scraped=Max('created_at')
).order_by('source__name')
楷模:
class Media(models.Model):
"""Media represents the medium where person(s) (entity?) can be
identified in.
"""
# Relations
#
# NOTE: persons can be generic foreign key to an 'entity', since
# we might consider organizations/brands
persons = models.ManyToManyField(
Person,
blank=True,
related_name="media",
help_text="Persons identified in the media",
)
reviews = GenericRelation(Review, related_query_name="media")
source = models.ForeignKey(
Source,
on_delete=models.SET_NULL,
blank=True,
null=True,
related_name="media",
help_text="Source for this media",
)
# Settings
STATUS_CHOICES = [
("active", "active"),
("inactive", "inactive"),
("under_review", "under review"),
]
status = models.CharField(
db_index=True,
max_length=64,
choices=STATUS_CHOICES,
default="inactive",
help_text="The status of this model, influences visibility on the "
"platform.",
)
# Data
title = models.TextField(
blank=True,
null=True,
help_text="Optional title of the media.",
)
class Source(models.Model):
"""Designates a source from which media originates
"""
TYPE_CHOICES = [
("entry", "entry"),
("scraper", "scraper"),
("unknown", "unknown"),
]
type = models.CharField(
max_length=64,
choices=TYPE_CHOICES,
default="unknown",
help_text="Type of source",
)
name = models.TextField(
blank=False,
null=False,
help_text="Domain name of the media where it originated from "
"(e.g. youtube, vimeo, mrdeepfakes)",
)
解决方案
Source
您应该对模型进行注释:
from django.db.models import Count, Max, Q
# since Django-2.0
Source.objects.annotate(
total=Count('media', filter=Q(media__created_at__gte=today)),
last_scraped=Max('media__created_at', filter=Q(media__created_at__gte=today))
).order_by('name')
这将生成 a QuerySet
ofSource
对象,其中每个Source
对象将具有两个额外的属性:包含大于或等于今天的相关对象.total
的总数,并且是大于 s的最大。Media
created_at
last_scraped
Max
created_at
today
None
如果存在Media
满足过滤器的 nu 相关对象,它将返回。
推荐阅读
- java - 如何在另一个代码运行时检测按键被按下
- sql-server - 我们如何在 SQL 中按日期计算新的不同值组
- laravel - Laravel Spatie 权限 多模型权限
- react-native - React Native - 在没有 Internet 连接的情况下将数据存储在本地 DB/AsyncStorage 中?
- reactjs - Nextjs中的未知帮助程序createSuper错误
- reactjs - 使用 useEffect 更新 JSX 变量“每次重新渲染后丢失”问题
- python - 是否有停止在 Python 中打印某些内容的功能?
- reactjs - How to load multiple components at same time in reactJs?
- uitableview - Why the cellForRowAt method is not getting called
- python - Cannot save animation: no writers available