Django query if field value is one of multiple choices

Posted by Nathan on Stack Overflow See other posts from Stack Overflow or by Nathan
Published on 2010-05-12T00:05:48Z Indexed on 2010/05/12 0:24 UTC
Read the original article Hit count: 543

Filed under:

Say I want to model a system where a piece of data can have multiple tags (e.g. a question on a StackOverflow is the data, it's set of tags are the tags). I can model this in Django with the following:

class Tag(models.Model):
    name = models.CharField(10)

class Data(models.Model):
    tags = models.ManyToManyField(Tag)

Given a set of strings, what's the best way to go about finding all Data objects that have one of these strings as the name of a tag in their tag list. I've come up with the following, but can't help thinking there is a more "Djangonic" way. Any ideas?

tags = [ "foo", "bar", "baz" ]
q_objects = Q( tags__name = tags[0] )
for t in tags[1:]:
    q_objects = q_objects | Q( tags__name = t )
data = Data.objects.filter( q_objects ).distinct()

© Stack Overflow or respective owner

Related posts about django