Brenden
Brenden

Reputation: 8774

Check if objects is foreign key of queryset result

I have a set of objects stored in a variable called subs. The column subscribed_to is a foreign object.

Is there any way to do check if a related_object is in this list in a simpler way:

def check_subscription_status(user, related_object):
    subs = get_user_subscriptions(user) # returns filter queryset
    subscribed = False
    for s in subs:
        if s.subscribed_to == related_object: #related object is the potential match
            subscribed = True
            break
    return subscribed

Upvotes: 1

Views: 221

Answers (1)

David Robinson
David Robinson

Reputation: 78640

return (related_object in [s.subscribed_to for s in subs])

ETA: A better way:

return subs.filter(subscribed_to=related_object).count() > 0

Upvotes: 1

Related Questions