基于多个关系对对象进行计数

时间:2019-06-14 22:28:34

标签: python django django-models django-orm

我有三种型号;

class User(AbstractUser):
    id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class UserProfile(Model):
    id = UUIDField(primary_key=True, editable=False)
    user = OneToOneField(User, CASCADE)
    subscription = CharField(max_length=250, null=True, blank=True)

class Image(Model):
    id = UUIDField(primary_key=True, editable=False)
    owner = ForeignKey(User, on_delete=CASCADE, null=True)

我想计算所有者订阅不等于字符串(例如“免费”)的所有Image对象。这可能吗?

1 个答案:

答案 0 :(得分:1)

您需要使用lookup that spans relationships

image_count = Image.objects.exclude(owner__userprofile__subscription='free').count()