Home > OS >  Sorting (order_by) in list
Sorting (order_by) in list

Time:10-14

I am building a BlogApp and I am trying to sort or order_by in list which contains multiple queries.

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 Comments(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    blog_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
    body = models.CharField(max_length=30)
    date_added = models.DateTimeField(auto_now_add=True)

views.py

def mypage(request):
    query_1 = list(BlogPost.objects.filter(user=request.user).order_by('-date'))

    query_2 = list(Comment.objects.filter(user=request.user).order_by('date_added'))


    results = sorted(chain(query_1, query_2),key=attrgetter('date') , reverse=True)

    context = {'results':results}
    return render(reques, 'mypage.html', context)

But is showing

'Comment' object has no attribute 'date'

And I think this is because date field name is different in both model and i am sorting with only one, But i have no idea how can I sort with different field name.

Any help would be much Appreciated. Thank You

CodePudding user response:

Or just add it as a property:

class Comments(models.Model):  # do NOT give a model a plural name!
    # ....
    @property
    def date(self):
        return self.date_added
        # or if it is a datetimefield
        # return self.date_added.date()

ALso you can just write a more customized sorting key (e.g. in case the involved models are from third-party apps).

def order(obj):
    try:
        return obj.date
    except AttributeError:
        return obj.date_added

# ...
results = sorted(chain(query_1, query_2), key=order, reverse=True)
  • Related