Django ORM 查询获取当前订阅用户的数量
我使用一个事件日志,该日志跟踪订阅和取消订阅以给定的邮件列表。
我的目标是一次(SQLITE)点击数据库以获取订阅用户的数量,我不需要对象,而是一个数字。
到目前为止
class MailingListEvent(models.Model):
"""Events on mailing lists.
This represents subscribes, unsubscribes, and bounces. We'd like
to understand what happens and when, not just the current state of
the system.
"""
class EventType(models.TextChoices):
SUBSCRIBE = 'sub', 'inscription'
UNSUBSCRIBE = 'unsub', 'désinscription'
BOUNCE = 'bounce', 'bounce'
user = models.ForeignKey(User, on_delete=models.CASCADE)
mailing_list = models.ForeignKey(MailingList,
on_delete=models.CASCADE)
event_timestamp = models.DateTimeField(default=django.utils.timezone.now)
event_type = models.CharField(max_length=6, choices=EventType.choices)
,我只找到了可以使用的解决方案:
def user_subscribe_count(mailing_list):
"""Return the number of users currently subscribed to the mailing list.
We want to know how many users are currently subscribed. Note
that individual users might subscribe and unsubscribe multiple
times. Other (future) events could happen as well.
"""
user_list = MailingListEvent.objects.filter(mailing_list=mailing_list).values_list('user',flat=True).distinct()
users_subscribed = list()
for user in user_list:
user_state = user_current_state(User.objects.get(pk=user),mailing_list)
if user_state.event_type == MailingListEvent.EventType.SUBSCRIBE:
users_subscribed.append(user_state)
return len(users_subscribed)
def user_current_state(user, mailing_list):
"""Return user's most current state on the provided mailing list
Return the most recent event associated with this user in this
mailing list.
"""
try:
the_user = MailingListEvent.objects.filter(
Q(event_type=MailingListEvent.EventType.SUBSCRIBE) |
Q(event_type=MailingListEvent.EventType.UNSUBSCRIBE),
user=user, mailing_list=mailing_list).latest(
'event_timestamp')
return the_user
except MailingListEvent.DoesNotExist:
return MailingListEvent(
user=user, mailing_list=mailing_list,
event_type=MailingListEvent.EventType.UNSUBSCRIBE)
我知道Django上有一个.count()方法,但是无论如何,转换为列表已经列出了数据库。
有人可以提出一个查询,该查询可以返回当前订阅此模型的用户数量吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 MailingList 添加最新的
MailingListEvent
来注释User
。 com/en/dev/ref/models/expressions/#subquery-expressions" rel="nofollow noreferrer">子查询
表达式[Django-doc]:如果最近的操作是
BOUNCE
,那么这将不被计为订阅用户。You can annotate the
User
s with the latestMailingListEvent
for thatMailingList
by using aSubquery
expression [Django-doc]:If the latest action was
BOUNCE
, then this will not be counted as a subscribed user.