How can I show a list in object.filter()?
When I load the page I'm only getting the queryset2 print to show a post. Which makes sense. but why does the queryset and queryset1 not show the posts with these categories?
models.py
class Post(models.Model):
ANALYSIS = "Analysis"
MILESTONE = "Milestone"
FEATURES = "Features"
TUTORIALS = "Tutorials"
CAREERS = "Careers"
COMMUNITY = "Community"
CATEGORY_CHOICES = [
(ANALYSIS, 'Analysis'),
(MILESTONE, "Milestone"),
(FEATURES, "Features"),
(TUTORIALS, "Tutorials"),
(CAREERS, "Careers"),
(COMMUNITY, "Community"),
]
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=125)
body = RichTextUploadingField(blank=True, null=True)
category = models.CharField(
max_length=20, choices=CATEGORY_CHOICES, default="watchlist"
)
views.py
class BlogFilterView(LoginRequiredMixin, FilterListViewDate):
model = Post
filterset_class = PostFilter
template_name = "dashboard/blog_filter.html"
paginate_by = 5
def get_queryset(self):
# categories = ["ANALYSIS", "MILESTONE", "FEATURES", "TUTORIALS", "CAREERS", "COMMUNITY",]
categories = ["Analysis", "Milestone", "Features", "Tutorials", "Careers", "Community",]
queryset = Post.objects.filter(category__icontains=categories)
print("queryset =", queryset)
queryset1 = Post.objects.filter(category__icontains="Analysis").filter(category__icontains="Milestone") \
.filter(category__icontains="Features").filter(category__icontains="Tutorials") \
.filter(category__icontains="Careers").filter(category__icontains="Community")
print("queryset1 =", queryset1)
queryset2 = Post.objects.filter(category__icontains="Community")
print("queryset2 =", queryset2)
return queryset
CodePudding user response:
You can use the in
operator to select all posts that have one of your categories:
categories = ["Analysis", "Milestone", "Features", "Tutorials",
"Careers", "Community"]
queryset = Post.objects.filter(category__in=categories)