Django - 如何从匹配不同值的视图中呈现值?

Django - How can I render a value from views that matches a different value?

我有两个列表:一个由用户添加的抽认卡组成,其中有一个 question 和一个 answer 字段(来自我的 Flashcard 模型)。另一个由歌曲中的单词组成。然后我制作了一个新列表,其中包含 question 与歌词重叠的单词(下面代码中的 user_word)。

现在,在我的 html 中,我想制作一个 table,在一栏中显示歌词中的单词,在第二栏中显示单词的含义,这(如果用户已经添加单词作为抽认卡)将是 answer 字段。

目前我的观点如下:

class SongVocab(LoginRequiredMixin, generic.DetailView):
    model= models.Song
    template_name = 'videos/song_vocab.html'
    context_object_name = 'song'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        from pymystem3 import Mystem
        m = Mystem()
        user_flash = Flashcard.objects.filter(owner=self.request.user).values_list('question', flat=True)
        lyrics_list = models.Song.objects.get().lyrics_as_list()
        user_flash_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(user_flash))]
        user_flash_clean = [w for w in user_flash_ if w.strip()]  ##removes empty strings
        lyrics_list_ = [item.replace('\n', ' ') for item in m.lemmatize(" ".join(lyrics_list))]
        lyrics_list_clean = [w for w in lyrics_list_ if len(w.strip())]
        user_word = list(set(user_flash_clean) & set(lyrics_list_clean))

        import icu # PyICU
        def sorted_strings(strings, locale=None):
            if locale is None:
                return sorted(strings)
            collator = icu.Collator.createInstance(icu.Locale(locale))
            return sorted(strings, key=collator.getSortKey)
        context['percent_known'] = ((len(user_word))/(len(set(lyrics_list_clean))))*100
        context['lyrics'] = sorted_strings(set(lyrics_list_clean),"ru_RU.UTF8")
        context['user_flash'] = user_flash_clean

        context['flash_answer'] = []
        for word in user_word:
            flash = Flashcard.objects.get(owner=self.request.user, question=word)
            context['flash_answer'].append(flash.answer)

    return context

我不知道如何将歌词这个词与用户抽认卡答案字段联系起来。我试过这个...

user_word = user_word
lyrics = lyrics_list_clean
context['test'] = {}
for word in user_word:
    flash = Flashcard.objects.get(owner=self.request.user, question=word)
    answer = flash.answer
    question = flash.question
    if question in lyrics:
        dict = {'lyric_word': question,'answer': answer}
        context['test'] = dict

...但它只给了我一个值,而不是每个词的正确值。我知道我的观点是错误的,我尝试过不同的方法,但到目前为止没有任何效果。我将不胜感激任何建议!我有点 需要对 user_word 列表中的歌词词进行“vlookup”,然后 return answer。我该怎么做?

我的html:

{% for item in lyrics %}
    <tr class='lyrics-table'>
        <td>{{item}}</td>
        <td>
        {% if item in user_flash %}
            <p>{{test.answer}}</p>
        {% else %}
            xxxx
        {% endif %}
        </td>
    </tr>
{% endfor %}

我还尝试了以下方法,这似乎是朝着正确方向迈出的一步,但我很难在我的模板中呈现它:

z = []
dict_lyrics = {'question': [], 'answer': []}
for word in user_word:
    x = lyrics_list_clean.index(word)
    y = user_word.index(word)
    flash = Flashcard.objects.get(owner=self.request.user, question=word)
    z.append(flash.answer)
    dict_lyrics['question'].append(lyrics_list_clean[x])
    dict_lyrics['answer'].append(z[y])
    context['question'] = dict_lyrics['question']
    context['answer'] = dict_lyrics['answer']
    context['dict_lyrics'] = dict_lyrics

更新 - 我在我的观点中添加了以下内容:

context['combined'] = list(zip(dict_lyrics['question'], dict_lyrics['answer']))

我可以在我的模板中像这样访问:

{% for i, j in combined %}
    {{ i }} -- {{ j }}
{% endfor %}

这有帮助,但没有解决我的问题...

我终于解决了我的问题,改变了我的观点如下:

from django.core.exceptions import ObjectDoesNotExist
z = []
dict_lyrics = {'question': [], 'answer': z}
for word in sorted_strings(set(lyrics_list_clean),"ru_RU.UTF8"):
   
    try:
        flash = Flashcard.objects.get(owner=self.request.user, question=word)
        z.append(flash.answer)
    except ObjectDoesNotExist:
        flash = ""
        z.append(flash)

    dict_lyrics['question'] = sorted_strings(set(lyrics_list_clean),"ru_RU.UTF8")
    context['question'] = dict_lyrics['question']
    context['answer'] = dict_lyrics['answer']
    context['dict_lyrics'] = dict_lyrics
    context['length'] = len(dict_lyrics['question'])
    context['combined'] = list(zip(dict_lyrics['question'], dict_lyrics['answer']))

然后在我的模板中:

 {% for item in combined %}
      <tr>
         <td>
           {{item.0}}
         </td>
         <td>
           {% if item.0 in user_flash %}
           {{item.1}}
           {% else %}
             xxx
            {% endif %}