ListView不相关的模型查找

时间:2019-08-21 14:41:56

标签: django django-models django-views

我正在寻找一种方法,用于将一个模型中的数据带入ListView的另一个模型的视图中。基本上,当用户打开词汇表的列表视图时,我需要使用vocab字段从字典模型中查找并拉出关联的拼音字段。在代码视图的底部有一些示例代码,这就是我如何将Vocabulary.vocabDictionary.pinyin进行匹配。

############### Models
​
class Vocabulary(models.Model):
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    vocab = models.CharField(max_length=255, blank=False, null=False)
    translation = models.CharField(max_length=255, blank=False, null=False)
    level = models.PositiveSmallIntegerField(blank=True, null=True, choices=LEVELS, default=0)
    audio = models.URLField(blank=True, null=True)
    objects = RandomManager()
​
    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['created_by', 'vocab'], name='User Vocab Duplicate Check')
        ]
        verbose_name = "Chinese Vocabulary"
        verbose_name_plural = verbose_name
​
    # this function will be invoked when this model object is foreign key of other model(for example Employee model.).
    def __str__(self):
        return self.vocab
​
class Dictionary(models.Model):
    traditional = models.CharField(max_length=20)
    simplified = models.CharField(max_length=20)
    pinyin = models.CharField(max_length=255)
    simplified_radical = models.CharField(max_length=20)
    hsk_level = models.PositiveSmallIntegerField(blank=True, null=True, choices=LEVELS, default=0)
    frequency_rank = models.PositiveIntegerField(blank=True, null=True)
    phrase_url = models.CharField(max_length=200)
    radical_url = models.CharField(max_length=200)
    definition = models.TextField()
    objects = RandomManager()
​
    class Meta:
        verbose_name = "Dictionary"
        verbose_name_plural = "Dictionary"
​
    def __str__(self):
        return self.simplified
​
################# Views
​
class VocabDetailView(LoginRequiredMixin, DetailView):
    model = Vocabulary
    template_name = 'library/vocab_details.html'
​
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['dictionary'] = Dictionary.objects.get(simplified=self.object.vocab)
        return context
​
​
class VocabListView(LoginRequiredMixin, ListView):
    model = Vocabulary
    template_name = 'library/vocab_list.html'
    paginate_by = 50

    def get_queryset(self):
        return Vocabulary.objects.filter(created_by=self.request.user)
​
    '''
    hao = Vocabulary.objects.get(vocab='你')
    haodict = Dictionary.objects.get(simplified=hao.vocab)
    haopin = hao_dict.pinyin
    '''

1 个答案:

答案 0 :(得分:0)

如果对象是相关的,则可以覆盖get_queryset以使用select_related或类似名称来获取相关对象。但由于对象之间没有关联,因此您似乎无法做到这一点。

因此,您要么不能使用ListView并在上下文中收集对象,要么无法覆盖上下文以获取所需的Dictionary对象。听起来你会做类似的事情;

def get_context_data(**kwargs):
    context = super().get_context_data(**kwargs)
    dicts = Dictionary.objects.filter(pinyin__in=self.object_list.values_list('vocab', flat=True))
    context['dictionaries'] = dicts
    return context