Django - how to filter on a comma seperated string

Viewed 609

At my Django models.py I have a "genre" field (models.TextField). This fields contains sometimes only one string and sometimes a comma separated list of string like this:

Comedy, Action, Drama

Or

Action, Fantasy

or as mentioned only one string e.g. only

Comedy

Now at my view I want to do something like this:

queryset_comedy = Movies.objects.get_queryset().filter(genre__in=["Comedy", "Family"])
queryset_action = Movies.objects.get_queryset().filter(genre__in=["Action", "Adventure"])
queryset_drama = Movies.objects.get_queryset().filter(genre__in=["Drama", "Thriller"])

I mentioned that my Query only matches field values which are standalone according to the genre field. For example Movie element one has the following genre string:

Comedy, Action

and Movie element Two only has "Comedy" as standalone string. Than the query outputs only Movie objects which have the string "Comedy" standalone and not Comedy, Action.

How can I make a Movie element match when multiple sorting strings are given for genre?

1 Answers

As an immediate solution, you could OR multiple contains queries together. I.e.

queryset_comedy = Movies.objects.filter(Q(genre__contains="Comedy") | Q(genre__contains="Family"))

However, I would recommend migrating to a more suitable representation, for example

Related