tags:

views:

33

answers:

1

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()
+2  A: 

Use the __in feature of queryset lookups. Specifically you can use tags__name__in in your example, as the documentation demonstrates.

Daniel DiPaolo
Thank You! This is exactly what I was looking for.
Nathan