¿Cómo filtro un resultado de la cadena ITerTools?
-
13-09-2019 - |
Pregunta
En mis puntos de vista, si importo un módulo ITerTools:
from itertools import chain
Y encadené algunos objetos con él:
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))
¿Cómo ordeno "ourtags" por "date_added"?
no sorprendentemente,
ourtags = list(chain(franktags, amytags, timtags, erictags)).order_by('date_added')
Devuelve un error "'Lista' no tiene ningún atributo 'Order_by'".
Solución
import operator
ourtags = sorted(ourtags, key=operator.attrgetter('date_added'))
Otros consejos
En este punto en el código, ya ha cargado todos los objetos en la memoria y en una lista. Simplemente ordene la lista como lo haría con cualquier lista antigua de Python.
>>> import operator
>>> ourtags.sort(key=operator.attrgetter('date_added'))
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow