Let's say I want to simulate a system in which part of the data can have several tags (for example, the question about StackOverflow is data, a set of tags are tags). I can simulate 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, the best way to find all Data objects that have one of these strings is as the tag name in the tag list. I came up with the following, but I can't help but think that 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()
source
share