views:

27

answers:

1

I have a bunch 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?

+1  A: 

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).

Mark