Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query if field value is one of multiple choices

Tags:

django

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()
like image 574
Nate Avatar asked Nov 24 '25 00:11

Nate


1 Answers

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

like image 113
Daniel DiPaolo Avatar answered Nov 25 '25 15:11

Daniel DiPaolo