The case of merging multiple lists into a list is encountered. Use the chain method to merge multiple lists. It can also be used to merge Django's QuerySet.
1. Python uses chain to merge multiple lists. Chain is realized by C, and it is reliable in natural performance. Here's a look at the basic usage:
#coding: Utf-8FromItertoolsImportChaina= [1,2,"AAA",{"Name":"Roy","Age":100}]B= [3,4]c = [5,6]#items = a + B + citems = Chain(a,b,c)for item in items: Print Item
The output results are as follows:
12aaa{' age ': + , ' name ': ' Roy '}3 456
2. The Django always merges multiple Queryset with chain. If you want to merge multiple queryset of the same model in Django, you can do so in this way.
#coding: Utf-8FromItertoolsImportChainFromYihaomen.Common.ModelsImport ArticleArticles1= Article.Objects.Order_by("Autoid").Filter(Autoid__lt= 16).Values(' Autoid ',' Title ')Articles2= article.. Filter (autoid = 30< Span class= "pun"). values ( ' autoid ' , articles = articles1 | articles2 # note the way it is used here. If the model is the same and is not sliced, and the field is the same, you can use print articles1 print Articles2print articles
this will work well. , but with some limitations, there are plenty of scenarios for Django, merging into a QuerySet and then returning to the template engine for processing.
/span> 3. Using chain to achieve, with chain to achieve will be more convenient, and not so many restrictions, even if the different model of the data, can be easily merged into a list.
#coding: Utf-8FromItertoolsImportChainFromYihaomen.Common.ModelsImport Article, UseridArticles1= Article.Objects.Order_by("Autoid").Filter(Autoid__lt= 16). values ( ' autoid ' , users = userid< Span class= "pun". objects. () items = Chainarticles1, Users) for item in Items: print item
Original address: Merging multiple Python lists and merging multiple Django QuerySet, thanks to the original author for sharing.
Merging multiple python lists and merging multiple Django QuerySet methods