Correct calls to annotated user set

This commit is contained in:
Mouse Reeve 2021-04-23 16:34:04 -07:00
parent 03e5da12dd
commit dda21195de
3 changed files with 26 additions and 15 deletions

View file

@ -1,5 +1,5 @@
""" store recommended follows in redis """
import math.floor
import math
from django.dispatch import receiver
from django.db.models import signals, Q
@ -41,17 +41,28 @@ class SuggestedUsers(RedisStore):
)
def get_stores_for_object(self, obj):
return [self.store_id(u) for u in self.get_users_for_object(obj)]
def get_users_for_object(self, obj): # pylint: disable=no-self-use
""" given a user, who might want to follow them """
return models.User.objects.filter(
local=True,
).exclude(user_following=obj)
).exclude(following=obj)
def rerank_obj(self, obj):
""" update all the instances of this user with new ranks """
stores = self.get_stores_for_object(obj)
pipeline = r.pipeline()
for store in stores:
pipeline.zadd(store, self.get_value(obj), xx=True)
for store_user in self.get_users_for_object(obj):
annotated_user = get_annotated_users(
store_user,
id=obj.id,
).first()
pipeline.zadd(
self.store_id(store_user),
self.get_value(annotated_user),
xx=True
)
pipeline.execute()
def rerank_user_suggestions(self, user):
@ -107,13 +118,13 @@ def add_or_remove_on_discoverability_change(
sender, instance, created, raw, using, update_fields, **kwargs
):
""" make a user (un)discoverable """
if not "discoverable" in update_fields:
if not update_fields or not "discoverable" in update_fields:
return
if created:
suggested_users.rerank_user_suggestions(instance)
if instance.discoverable:
suggested_users.add_object_to_related_stores(instance)
suggested_users.rerank_obj(instance)
elif not created and not instance.discoverable:
suggested_users.remove_object_from_related_stores(instance)

View file

@ -46,5 +46,5 @@ class Directory(View):
def post(self, request):
""" join the directory """
request.user.discoverable = True
request.user.save()
request.user.save(update_fields=["discoverable"])
return redirect("directory")

View file

@ -207,27 +207,27 @@ def get_suggested_users(user):
)
def get_annotated_users(user, *args, **kwargs):
def get_annotated_users(viewer, *args, **kwargs):
""" Users, annotated with things they have in common """
return (
models.User.objects.filter(discoverable=True, is_active=True, *args, **kwargs)
.exclude(Q(id__in=user.blocks.all()) | Q(blocks=user))
.exclude(Q(id__in=viewer.blocks.all()) | Q(blocks=viewer))
.annotate(
mutuals=Count(
"following",
filter=Q(
~Q(id=user.id),
~Q(id__in=user.following.all()),
following__in=user.following.all(),
~Q(id=viewer.id),
~Q(id__in=viewer.following.all()),
following__in=viewer.following.all(),
),
distinct=True,
),
shared_books=Count(
"shelfbook",
filter=Q(
~Q(id=user.id),
~Q(id=viewer.id),
shelfbook__book__parent_work__in=[
s.book.parent_work for s in user.shelfbook_set.all()
s.book.parent_work for s in viewer.shelfbook_set.all()
],
),
distinct=True,