Django query if field value is one of several options

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()
+3
source share
1 answer

Use __inthe query search function . In particular, you can use tags__name__inin your example, as the documentation shows.

+3
source

Source: https://habr.com/ru/post/1745022/


All Articles