Dumarkus
Dumarkus

Reputation: 1

How to filter django python object with list

I have the following django models

class Article(models.Model): 
article_tags = models.CharField(max_length=200, blank=True, null=True)

class UserProfile(models.Model): 
user_interests = models.CharField(max_length=200, blank=True, null=True)

I have a feed feature for my users and want to filter articles based on user_interests.

For example I have a user with user_interests = ['horror', 'comedy', 'fiction'].

And I have articles with article_tags which are also lists = ['funny', 'comedy', 'new york']

I want to filter my users' feeds by comparing their user_interests with the article_tags of all the articles.

I had tried this:

user_interested_articles =  Article.objects.filter(case_tags__in =
user_interests)

But it doesn't work, I believe this is because I'm trying to compare a list with a list. Is there another way to do this?

Upvotes: 0

Views: 59

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599956

You shouldn't be storing lists in a char field - or indeed at all. These are tags, and should be stored in a separate model. You can use an app like django-taggit for this.

Upvotes: 2

pleasedontbelong
pleasedontbelong

Reputation: 20102

you could normalize your models, and create a new model Tag. (ManyToMany to UserProfile and Article

Then you'll be able to query something like:

Article.objects.filter(case_tags__in =user.user_interests)

Hope this helps

Upvotes: 1

Related Questions