designkai
designkai

Reputation: 15

Counting objects based on multiple relationships

I've got three models;

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)

I would like to count all Image objects where the owners subscription doesn't equal a string (eg 'free'). Is this possible?

Upvotes: 0

Views: 29

Answers (1)

severestrength
severestrength

Reputation: 312

You need to use a lookup that spans relationships.

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

Upvotes: 1

Related Questions