Issue
I am building a Blog App and I am trying to access first posts of all the users
in last 2 days
, So i am using solution for accessing first posts.
when i use filter of last 2 days
then the first post method is not working. So i thought "I should use filter in another query"
models.py
class BlogPost(models.Model):
user= models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=30, default='')
body = models.CharField(max_length=30, default='')
date = models.DateTimeField(auto_now_add=True)
views.py
def first_posts(request):
time = timezone.now() - timedelta(days=2)
posts = [user.blogpost_set.first() for user in User.objects.prefetch_related(
'blogpost_set')].filter(blogpost__date__gte=time)
context = {'posts':posts}
But it showed
'list' object has no attribute 'filter'
- I also tried using :-
ALL_POSTS = []
for post in posts:
ALL_POSTS.append(post).filter(post__date=time)
But it showed
'NoneType' object has no attribute 'filter
I will really appreciate your Help.
Thank You
Solution
You can use group by user query as a subquery.
two_days_ago = timezone.now() - timedelta(days=2)
# get first blog_post_id user-wise in last two days
post_ids_subquery = BlogPost.objects.filter(
date__gt=two_days_ago
).values(
'user'
).annotate(
min_id=Min('id')
).values('min_id')
# get objects for that blog_post_ids for accessing all fields of models
queryset = BlogPost.objects.filter(id__in=post_ids_subquery)
Edit: post_ids_subquery query is similar to:
print(post_ids_subquery.query)
SELECT MIN(`blog_post`.`id`) AS `min_id` FROM `blog_post` WHERE `blog_post`.`created_at` > {two_days_ago} GROUP BY `blog_post`.`user_id`
when you apply group_by query then its gets user_wise data then applying Min('id') function , it gets minumum id of each user_wise data. Since id is auto-incremental id , so min_id gives first blog_post_id for each user.
Answered By - shahbaz ahmad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.