Home > Blockchain >  Using order_by date in list
Using order_by date in list

Time:09-28

I am building a Blog App and I am accessing different models query and adding them in a single list and I am trying to order_by('-date') in the list.

Name date is all same in all models.

models.py

class BlogPost(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=30)
    date = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
    comment_by = models.ForeignKey(User, on_delete=models.CASCADE)
    post_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
    body = models.CharField(max_length=30)
    date = models.DateTimeField(auto_now_add=True)

class Like
    ....
    date = models.DateTimeField(auto_now_add=True)


class Dislike
    ....
    date = models.DateTimeField(auto_now_add=True)

views.py

def list_page(request,blogpost_id):
    post = get_object_or_404(BlogPost, id=blogpost_id)

    comments = []

    for q1 in post.comment_set.all()
        comments.append(q1)

    likes = []

    for q2 in post.like_set.all()
        likes.append(q2)


    dislikes = []

    for q3 in post.dislike_set.all()
        dislikes.append(q3)

    # Mixing all the lists
    all_lists = sum([comments,likes,dislikes], []) 

    context = {'all_lists':all_lists}
    return render(request, 'listPage.html', context)
  • I also tried by adding order_by('-date') But it showed

'list' object has no attribute 'order_by'

  • I tried like .all().order_by('-date') but it was only effecting on query.

I will really appreciate your Help. Thank You

CodePudding user response:

you can try to chain them something like this in your views.py.

from itertools import chain
all_lists = sorted(chain(comments,likes,dislikes),key=lambda x:x.date,reverse=True)

reverse = True is used to change the order of the list by default is False.it is up to you to change it. The best solution for this is to try to get the comments,dislikes ,likes inside the template

CodePudding user response:

Try using sort() method. Here's an example that might help.

from datetime import datetime
my_dates = ['5-Nov-18', '25-Mar-17', '1-Nov-18', '7-Mar-17']
my_dates.sort(key=lambda date: datetime.strptime(date, "%d-%b-%y"))
print(my_dates)
  • Related