获取两个表中引用的对象数

时间:2014-08-30 02:03:23

标签: django

我有以下两种型号。我想获得两个表中的用户对象的数字

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

现在

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

这显然是获得unique_count的可怕方式。什么是更好的计算方法?

1 个答案:

答案 0 :(得分:2)

试试这个:

首先为冲突类型设置related_name

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

然后,使用Q objects,你可以做这样的事情

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