Select distinct users with referrals
I have a bunch开发者_如何学JAVA of Users
. Since Django doesn't really let me extend the default User
model, they each have Profiles
. The Profiles have a referred_by
field (a FK to User). I'm trying to get a list of Users with >= 1 referral. Here's what I've got so far
Profile.objects.filter(referred_by__isnull=False).values_list('referred_by', flat=True)
Which gives me a list of IDs of the users who have referrals... but I need it to be distinct, and I want the User
object, not their ID.
Or better yet, it would be nice if it could return the number of referrals a user has.
Any ideas?
Took me a long time to wrap my head around this, but I think I finally got it figured out:
affiliates = User.objects.annotate(num_referrals=Count('referrals')).filter(num_referrals__gt=0)
I didn't think I'd be able to use the reverse relationship
referred_by = models.ForeignKey(User, null=True, blank=True, related_name='referrals')
in Count()
, nor did I think you could use the annotated value in the filter... that's pretty cool. I still wish you could use GROUP BY without having to annotate stuff (assuming I didn't need the count).
精彩评论