[Answer]-Django – sort objects – need some help in logic

1πŸ‘

βœ…

I assume you are using latest_entry() in other places too, so just create another method latest_added_time() which returns latest_entry.added or a fake time.

class TopicCenter(models.Model):
    ...
    def latest_added_time(self):
        latest = self.latest_entry()
        if latest:
            return latest.added
        else:
            # returns a time to place it at the end of the sorted list
            return datetime(1, 1, 1) 

Then, you can just sort on this new method:

tcss = TopicCenter.objects.all().distinct('id')  
sorter = lambda x: x.latest_added_time()
tcs = sorted(tcss, key=sorter, reverse=True)

If you aren’t using latest_entry() for anything else, then you should just put this logic directly into that function.

πŸ‘€pcoronel

0πŸ‘

You can try by changing your conditions

if not book and not journal:
    #Action you want to perform

or you can see if lastone list is empty you can append any message there like

if not len(lastone):
    #Your code to append a message
πŸ‘€S.Ali

Leave a comment