Nate
Nate

Reputation: 7079

Django query if field value is one of multiple choices

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()

Upvotes: 3

Views: 2172

Answers (1)

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

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

Upvotes: 3

Related Questions