【发布时间】:2020-06-27 23:21:47
【问题描述】:
我正在将视图中的数据渲染到我的模板中,如下所示:
<tbody>
{% for item in lyrics %}
<tr class='lyrics-table'>
<td>{{item}}</td>
<td>
{% if item in user_flash %}
<p>{{flash_answer}}</p>
{% else %}
<p>xxx</p>
{% endif %}
</td>
我的看法如下:
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 呈现相关的flash_answer?目前,我得到了整个查询集,这是有道理的,因为这就是flash_anwswer。但这两者是联系在一起的,所以一定有办法,但我不知道该怎么做。我是否需要更改视图,或者有什么方法可以在模板中以不同方式呈现它?
更新 - 我现在认为我需要在我的视图中创建一个字典,但我不知道该怎么做。所以我有:
user_word - 给出一个列表,其中包含用户的抽认卡与歌词中的单词重叠的单词。
那么我现在怎样才能得到一个显示例如的字典:
{'question': relevant word from lyrics, 'answer': flash_answer}
但是我怎样才能将两者匹配并获得“歌词中的相关单词”?几乎就像在 excel 中进行 vlookup... 我完全迷路了!
更新:我试过了,这很有效,但我只得到一个值而不是全部......
z = []
m = {'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)
m['question'].append(lyrics_list_clean[x])
m['answer'].append(z[y])
context['test'] = m
【问题讨论】:
标签: python python-3.x django django-views django-templates