emnoor
emnoor

Reputation: 2708

Get the number of objects that is referenced in two tables

I have following two models. I want to get the number of user objects that are in both tables.

class Share(models.Model):
    user = models.ForeignKey(User)
    blog = models.ForeignKey(Blog)
    # more code

class Follow(models.Model):
    follower = models.ForeignKey(User)
    followee = models.ForeignKey(User)
    # more code

Now

shares = Share.objects.filter(blog=some_blog)
follows = Follow.objects.filter(followee=some_user)

share_users = [share.user for share in shares]
followers = [follow.follower for follow in follows]

unique_count = len(set(share_users + followers))

This is obviously horrible way to get unique_count. What could be a better way to get this count?

Upvotes: 1

Views: 61

Answers (1)

karthikr
karthikr

Reputation: 99660

Try this:

First set related_name for the conflicting types

class Follow(models.Model):
    follower = models.ForeignKey(User, related_name="follower")
    followee = models.ForeignKey(User, related_name="followee")

and then, using Q objects, you can do something like this

from django.db.models import Q
unique_user_count = User.objects.filter(
                         Q(share__isnull=False) 
                       | Q(follower__isnull=False) 
                       | Q(followee__isnull=False)).distinct().count()

Upvotes: 2

Related Questions