Reputation: 33
I have a Post model in Django that looks like this:
class Post(models.Model):
post = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)
I would like to sort and display posts per day per user. So if one user made 20 posts on Monday and another made 15 posts on Tuesday and 4 on Wednesday they would be grouped together and displayed. I don't need the total count of posts per user or day just a way to separate all posts made per day by user to display them together.
Example (would like to display on one page): Monday: user 1: post1, post2, post2. user 2: post1 post2, post3, post4, post5. Tuesday: user2: post1, post2, post3. user3: post1, post 2....for all posts and users
I've tried posts = Post.objects.all().order_by('-timestamp','user')
it displays all posts but I can't figure out how to group the post by user per day.
Upvotes: 0
Views: 178
Reputation: 33
I figured it out. I needed to nest regroup. The following code works. This took me two days to figure out.
{% regroup posts by timestamp|date as date_list %}
{% for time in date_list %}
{% regroup time.list by user as user_list %}
{% for user in user_list %}
<div class="card" style="width: 30rem;">
<div class="card-body">
<div>
<img src="{{ user.grouper.profile_pic.url }}" class="rounded-circle mr-3" height="50px" width="50px" alt="avatar" style="float:left">
<a href="{% url 'profile' user.grouper.id %}"><h5>@{{user.grouper}}</h5></a>
</div>
<p class="card-title">{{ time.grouper}}</p>
{% for x in user.list %}
<li><p class="card-text">{{ x.post}}</p></li>
{% endfor %}
</div>
{% endfor %}
</div>
{% endfor %}
Upvotes: 1
Reputation: 1596
You should order by truncated date first, and then by user, and then later by timestamp, for results to be always the same. No ordering of posts may change order of them in unpredictable manner. Like this:
posts = Post.objects.all().order_by(TruncDate('timestamp').desc(),'user','timestamp')
Upvotes: 1