首页 > 解决方案 > 即使为零也获取记录数

问题描述

我的脚本中有以下查询,它返回每个源名称今天添加的记录数。我添加了一个过滤器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)",
    )

标签: django

解决方案


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 QuerySetofSource对象,其中每个Source对象将具有两个额外的属性:包含大于或等于今天的相关对象.total的总数,并且是大于 s的最大。Mediacreated_atlast_scrapedMaxcreated_attoday

None如果存在Media满足过滤器的 nu 相关对象,它将返回。


推荐阅读