0

Profiles have tags. I'm rendering a list of profile_tags and top_tags. How would I go about checking if each tag in top_tags is in profile_tags?

What I've tried in my views:

has_tag = False
profile_tags = profile.tags.all()
top_tags = Tag.objects.all()
for top in top_tags:
    if top in profile_tags:
        has_tag = True

Thank you in advance for your help!

2 Answers 2

1

You can do:

has_tag = set(list(top_tags)).issubset(list(profile_tags))

This gives you the boolean flag.

Sign up to request clarification or add additional context in comments.

9 Comments

list() returns a list not a boolean value, and your new edit makes your solution exactly same as mine.
I'm given a TypeError:'bool' object is not iterable
sorry.. the list() wrap was my mistake.
@karthikr When rendering to the template: I have {% if has_tag %}Remove{% else %}Add{% endif %}. But it seems to never hit the else to show 'Remove'. Would you know how to make the check work?
check the value of has_tag - the template should go by the default True or False boolean. One way to check is - just do {{has_tag}} and see the value
|
1

Convert both of them to sets and check if set of top_tags is a subset of set of profile_tags:

In [14]: profile_tags=[1,2,3,4]

In [15]: top_tags=[1,2,3]

In [16]: s1=set(profile_tags)

In [17]: s2=set(top_tags)

In [18]: s2.issubset(s1)
Out[18]: True

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.