簡體   English   中英

如何在Django Haystack中的相關模型中解決過濾問題

[英]How to address filtering in related models in django haystack

我有以下型號:

class Note(models.Model):
    user = ForeignKey(User)
    topic = CharField(max_length=20)

class Referral(models.Model):
    recipient = ForeignKey(User, related_name=referral_rcvd)
    giver = ForeignKey(User, related_name=referral_given)
    about = CharField(max_length=20)

以及search_indexes.py的以下內容:

class NoteIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, use_template=True)
    topic = indexes.CharField(model_attr='topic')

我想在模板中看到的是:

Search for: <topic>

Results:
<ul>
<topic> <topic.user.username> <topic.user.referral_rcvd.filter(about=topic)
</ul>

在shell中工作,因此更容易,這給了我我想要的東西:

from haystack.query import SearchQuerySet as SQS
from models import *
s = SQS().models(Note).auto_query('topic_name')
[i.object.user.referral_rcvd.filter(about=i.object.topic).count() for i in s.all()]

但這在html模板中不起作用:

{% for result in object_list %}
   {{ result.object.user.referral_rcvd.filter(about=i.object.topic).count() }}
{% endfor %}

如果它在外殼中有效,如何在模板中使其有效? 謝謝!

終於解決了! 我所做的是使用prepare_FOO方法:

class NoteIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, use_template=True)
    topic = indexes.CharField(model_attr='topic')
    referral_count = indexes.IntegerField()

    def prepare_referral_count(self, obj):
        topic_name = Note.objects.get(pk=obj.pk).topic
        return obj.user.referral_rcvd.filter(about=topic_name).count()

然后,我運行python manage.py update_index並將以下內容放入模板中:

{% for result in object_list %}
   {{ result.referral }}
{% endfor %}

它不是result.object.referral因為我們要引用索引中的某些內容。

暫無
暫無

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

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