how do i filter an itertools chain() result?
-
13-09-2019 - |
Question
in my views, if i import an itertools module:
from itertools import chain
and i chain some objects with it:
franktags = Frank.objects.order_by('date_added').reverse().filter(topic__exact='art')
amytags = Amy.objects.order_by('date_added').reverse().filter(topic__exact='art')
timtags = Tim.objects.order_by('date_added').reverse().filter(topic__exact='art')
erictags = Eric.objects.order_by('date_added').reverse().filter(topic__exact='art')
ourtags = list(chain(franktags, amytags, timtags, erictags))
how do i then order "ourtags" by the "date_added"?
not surpisingly,
ourtags = list(chain(franktags, amytags, timtags, erictags)).order_by('date_added')
returns an "'list' object has no attribute 'order_by'" error.
Solution
import operator
ourtags = sorted(ourtags, key=operator.attrgetter('date_added'))
OTHER TIPS
By this point in the code, you've already loaded up all of the objects into memory and into a list. Just sort the list like you would any old Python list.
>>> import operator
>>> ourtags.sort(key=operator.attrgetter('date_added'))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow