I have Topiccenter Model:
class TopicCenter(models.Model):
title = models.TextField()
def latest_entry(self):
latest_entries = []
book = self.tc_books.order_by('-id')[:1]
journal = self.tc_journals.order_by('-id')[:1]
if book:
for b in book:
if b:
latest_entries.append(b)
if journal:
for jn in journal:
if jn:
latest_entries.append(jn)
lastone = []
if latest_entry:
lastone = max(latest_entries, key = lambda x: x.added)
return lastone
# what to return here if lastone is empty list ?? :(
each topiccenter can have many books and journals. I want to get the latest entry by its added field.
I am sorting now topiccenters by the date of its latest entry. Now the Problem i am facing is, some topiccenters are totally empty (no book, no journals) so i dont know what to return in latest_entry() method if latest_entry is [] so that I can use it here like this:
tcss = TopicCenter.objects.all().distinct('id')
sorter = lambda x: x.latest_entry().added
tcs = sorted(tcss, key=sorter, reverse=True)
at this moment i am getting 'list' object has no attribute 'added' because one Topiccenter has neither book nor journal, so latest_entry() is returning [] which causing the error message.
can someone please help me how to solve this logic :(