簡體   English   中英

有沒有辦法從 get_queryset 返回兩個組合列表,而不僅僅是查詢集?

[英]Is there a way to return two combined lists from get_queryset instead of just the query set?

我正在使用 Django 生成一個 generic.ListView 對象。 我也在使用 Elastic Search 搜索結果。 我的問題是如何將我的查詢集與 JSON 對象的有序列表結合起來? get_queryset只允許我返回一個變量(查詢集),但我需要get_context_data才能訪問查詢集和搜索結果的相關元數據。 我創建了一個下面的 hack,它可以工作,但正在尋找更好的解決方案。

def get_queryset(self):
    # just get 2 documents, in my actual code the queryset is generated by a list of IDs
    # from the Elastic Search query
    qs = Document.objects.all()[:2] 
    # create some fake search results, in my actual code I get a similar looking JSON 
    # objects with metadata like result score or highlighted snippets from the search corpus
    fake_results = [
            { 'meta': {
                'highlight': {
                    'title': ['ABC'],
                    'content': ['123', '456'],
                    }
                }
            },
            { 'meta': {
                'highlight': {
                    'content': ['789'],
                    }
                }
            }
            ]

    # this is a hack (i think) but need to merge the metadata from search results into the queryset object                
    for doc, result in zip(qs, fake_results): 
        if 'highlight' in result['meta']:
            doc.snippet = result['meta']['highlight']

    return qs

def get_context_data(self, **kwargs):
    """ do stuff with the modified queryset """

您可以從 get_queryset 返回任何可迭代對象。 您可以返回 zip(qs, fake_results),但您應該正確地解壓它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM