1

To clarify, I'm not asking for Article.objects.filter(headline__in=['Doge', 'Cat', 'Lizard']) instead I want to do it the other way around. Kinda like this logic

q = Q()
for word in headline.split():
    q |= Q(keywords__keyword__icontains=word)
KeywordSubscription.objects.filter(q).all()

Something akin to that. I'm not sure if there's a shortcut or maybe some sort of function that gives me access to what I need.

Input: 'Cats are taking over the world!'

My table is a mapping between User and Keywords (many to many field):

class KeywordSubscription(models.Model):
    user = models.OneToOneField(User, unique=True)
    keywords = models.ManyToManyField(Keyword)
    objects = KeywordSubscriptionManager()


class Keyword(models.Model):
    keyword = models.CharField(max_length=128)

Each user can be subscribed to a couple of keywords, so for example say that user_0 is subscribed to cat, and user_1 is subscribed to dog, the above query would be looping over: ['Cats', 'are', 'taking', 'over', 'the', 'world'] and checking for the user that's subscribed to any of those words

Clarification 2: The code works, it's just not elegant.

EDIT:

it ended up looking like so

query = reduce(operator.or_, (Q(keywords__keyword__iexact=word) for word in instance.headline.split()))
Stupid.Fat.Cat
  • 10,755
  • 23
  • 83
  • 144
  • Can you add an input and expected output please? – cdvv7788 Jan 28 '17 at 01:34
  • @cdvv7788 added the models and more context as well. – Stupid.Fat.Cat Jan 28 '17 at 01:38
  • 1
    Something like http://stackoverflow.com/questions/4824759/django-query-using-contains-each-value-in-a-list should help you with the lookup for the list. You can start on the keyword model, find all those that match, and then do: KeywordSubscription.objects.filter(keywords=result_keywords) That would require 2 queries tho. – cdvv7788 Jan 28 '17 at 01:56
  • This is what you are looking for: https://stackoverflow.com/a/55016167/10856743 – Oscar Chen Jun 28 '21 at 01:11

0 Answers0