I simulate Instagram app.
I have Followers, Actions models.
Each action is done on a “follower”.
Many actions can point to one follower.
JavaScript
x
15
15
1
class Follower(models.Model):
2
identifier = models.BigIntegerField(
3
_("identifier"), unique=True, null=False, blank=False)
4
5
class ActionModel(models.Model):
6
target = models.ForeignKey(Follower, verbose_name=_("Target"),
7
on_delete=models.CASCADE) # username of the done-on action
8
user = models.ForeignKey(
9
settings.AUTH_USER_MODEL,
10
on_delete=models.CASCADE,
11
null=True,
12
) # django user that performed the action
13
is_followed_back = models.BooleanField(_("Followed Back"), null=True,
14
blank=True) # is target followed back
15
Admin panel:
JavaScript
1
15
15
1
# Custom Admin for Follower model
2
class FollowerAdmin(AdminAdvancedFiltersMixin, NumericFilterModelAdmin, SpecialActions):
3
4
# Private method to count been_followed_counter
5
def _get_been_followed_count(self, obj):
6
return obj.been_followed_count
7
_get_been_followed_count.short_description = 'Been Followed Count'
8
_get_been_followed_count.admin_order_field = 'been_followed_count'
9
10
# Private method to count follow_back_count
11
def _get_follow_back_count(self, obj):
12
return obj.follow_back_count
13
_get_follow_back_count.short_description = 'Follow Back Count'
14
_get_follow_back_count.admin_order_field = 'follow_back_count'
15
I then override the get_queryset for followers:
JavaScript
1
14
14
1
# Override queryset method to add count's
2
def get_queryset(self, request):
3
4
qs = super().get_queryset(request)
5
6
qs = qs.annotate(
7
been_followed_count=Count('actionmodel', filter=Q(actionmodel__user=request.user))
8
).annotate(
9
follow_back_count=Count(
10
'actionmodel',
11
filter=Q(actionmodel__user=request.user) & Q(actionmodel__is_followed_back=True)
12
)
13
)
14
I get really strange results in the admin panel: no search in panel
USERNAME : lior___shahar
BEEN FOLLOWED COUNT:5
FOLLOW BACK COUNT:5
This is the True VALUE in actions: Value in action
But once I do SEARCH in FOLLOWERS for the username: After Search
USERNAME : lior___shahar
BEEN FOLLOWED COUNT:320
FOLLOW BACK COUNT:320
…
I don’t get what is wrong.
Advertisement
Answer
Try adding distinct=True
to the count annotation.
JavaScript
1
2
1
been_followed_count=Count('actionmodel', filter=Q(actionmodel__user=request.user), distinct=True)
2