Reputation: 2952
What is the most Pythonic way to sort on different fields a list that may contain two distinct types of Django model objects? Here's an example:
The models:
class A(models.Model):
creation_time = models.DateTimeField()
class B(models.Model):
last_updated = models.DateTimeField()
The view:
a = A.objects.all().order_by('creation_time')
b = B.objects.all().order_by('last_updated')
c = list(chain(a, b))
# Now I want to organize the contents of c by date pertaining to each object.
How can I sort with different keys on each object?
Upvotes: 0
Views: 72
Reputation:
Sort the list c
in place using
c.sort(key=lambda x: getattr(x, 'creation_time', None) or getattr(x, 'creation_date', None))
Upvotes: 3