How do I filter the result of itertools chain ()?

in my views, if I import the itertools module:

from itertools import chain

and I associate 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 order ourtags with date_added then?

not surpisingly

ourtags = list(chain(franktags, amytags, timtags, erictags)).order_by('date_added')

returns a "list" object, does not have the "order_by" attribute. Mistake.

+3
source share
2 answers
import operator

ourtags = sorted(ourtags, key=operator.attrgetter('date_added'))
+12
source

At this point in the code, you have already loaded all the objects into memory and into the list. Just sort the list like any old Python list.

>>> import operator
>>> ourtags.sort(key=operator.attrgetter('date_added'))
+5
source

Source: https://habr.com/ru/post/1712641/


All Articles