Best way to find a tag among an array of tag objects in Django
I'm using django-tagging and I've got an array of tag objects. What's the best way to d开发者_开发问答etermine whether a given tag is among them?
def is_new (self):
tags = Tag.objects.get_for_object(self)
tagged = False
for tag in tags:
if tag = 'new':
tagged = True
return tagged
I have never really used django tagging but looking through the source really quickly the .get_for_object returns a queryset of the tags for that object. Not an actual list.
I'm not sure if your code is working [appart from the assignment/comparison issue] or if you just want to improve it. But Since you are returning a queryset couldn't you continue filtering it for instance:
Tag.objects.get_for_object(self).filter(name='new')
or to be able to use JamesO's example of:
if 'new' in tags: return True
I think you need to turn the queryset into a list first.
list(tags)
And then it should work.
See documentation for forcing list evaluation - and note the memory concerns of doing that.
So my recommendation would be testing filtering first - and let us know if it works, because now I got curious.
tags = Tag.objects.get_for_object(self)
if 'new' in tags:
return True
精彩评论