0

The reason I need this is to show activity thread in reverse chronological order. I achieve that by chaining multiple objects into one and then displaying in one place. Currently I have:

contacts = User.contact_created_by.all()
companies = User.company_created_by.all()
tasks = User.tasks_created_by.filter(isComplete=True)
activity = sorted(
       chain(contacts, companies, tasks),
       key=lambda instance: instance.created_on, reverse=True)

But I need tasks to be sorted by "completion_date" and not by "created_on" date in the resulting object.

I tried this for lambda function:

key=lambda instance: instance.complete_date if (isinstance(instance, Task)) else instance.created_on, reverse=True)

but since "contact" and "company" models do not have "complete_date" fields, I get an error.

Basically the problem is to combine different objects and sort them by different fields (but same type - date!). For example, I further plan to add "event" object to the project which would need to be shown in activity thread, with some type of "event_date".

So the result would be something like the following (in the reverse chronological order):

Today:

-event X happened
-contact X created
-task X completed

Yesterday:

-task Y completed
-company X created

The day before yesterday:
-company Y created
templargin
  • 11
  • 3

1 Answers1

0

Try this: sort values with None

sorted(
    instances, 
    key=lambda i: (getattr(i, 'complete_date', None) is None, getattr(i, 'complete_date', None))
)
minglyu
  • 2,958
  • 2
  • 13
  • 32
  • Sorry for taking so long to respond. I ended up creating a whole separate model called 'Activity', because my approach was not scalable. Thank you anyway. – templargin Aug 28 '20 at 21:22