如何在模板(django)中显示在线好友总数?

How to show the total count of online friends in the template (django)?

这是我的用户模型-

class CustomUser(AbstractUser):

  user_id = models.UUIDField(default=uuid.uuid4,editable=False,primary_key=True)
  username = models.CharField(max_length = 100,unique = True)
  friends = models.ManyToManyField('CustomUser',related_name="friend", blank= True)
  user_last_seen = models.DateTimeField(auto_now_add=False)

我可以使用以下中间件跟踪用户最后一次被看到的时间(无论他们是否注销):

class ActiveUserMiddleware(MiddlewareMixin):

  def process_request(self, request):
      current_user = request.user
      if request.user.is_authenticated:
        now = datetime.datetime.now()
        current_user.user_last_seen = now
        current_user.save(update_fields=['user_last_seen'])

并且还能够在我的模板中显示它们当前是否处于活动状态,或者它们最后一次出现的时间 -

 {%if i.user_last_seen|timesince|upto:',' < "1 minutes" %}
 <td style="font-size:small; color:green;text-align:right;">
 Active Now
 </td>
 {%else%}
 <td style="font-size:small; color:gray;text-align:right;">
 {{i.user_last_seen|timesince|upto:','}} ago
 </td>
 {%endif%}

与此同时,我想显示当前活跃的用户总数,他们是特定用户的朋友。但我很难理解如何做到这一点。说到 Django,我还是个初学者,任何建议或想法都会很有帮助。

您可以计算不到一分钟前最后一次看到的人数:

from django.utils.timezone import now
from datetime import timedelta

active_users = CustomUser.objects.filter(
    <b>user_last_seen__gte=now()-timedelta(minutes=1)</b>
).count()

或活跃好友数:

from django.utils.timezone import now
from datetime import timedelta

active_friends = request.user.friends.filter(
    <b>user_last_seen__gte=now()-timedelta(minutes=1)</b>
).count()

因此您可以在视图或上下文处理器中使用它来将活动用户数传递给模板。

您还可以在 CustomUser 中定义逻辑以检查用户是否处于活动状态:

from django.utils.timezone import now
from datetime import timedelta

class CustomUser(AbstractUser):
    user_id = models.UUIDField(default=uuid.uuid4,editable=False,primary_key=True)
    username = models.CharField(max_length = 100,unique = True)
    friends = models.ManyToManyField('CustomUser', blank= True)
    user_last_seen = models.DateTimeField(auto_now_add=False)

    @property
    def <b>recently_active</b>(self):
        return self.user_last_seen >= now()-timedelta(minutes=1)