In this particular case ModelA is the default Django models.User
ModelB is implemented as :
class ModelB(models.Model):
user = models.ManyToManyField(User)
#some other stuff
1. For each ModelB record, count the User records which don't have a relationship with it
I managed to do that using :
ModelB.objects.all().annotate(user_count=User.objects.count()-Count('user'))
It works but feels like a hack. Is there a better way to do this (while still using annotate()
) ?
2. With filtering
I modified my previous query to be filtered with the currently logged in User so I can display custom content for each user. I intended to keep the same user_count
value as in query #1 regardless of the logged in user:
ModelB.objects.filter(
user=request.user
).annotate(
user_count=User.objects.count()-Count('user')
)
EDIT : Filtering works as expected when it's done after annotate
:
ModelB.objects.annotate(
user_count=User.objects.count()-Count('user')
).filter(
user=request.user
)
Still looking for something better than User.objects.count()-Count('user')
to count non-related user records for each ModelB
record.
Thanks for helping !