[英]How to address filtering in related models in django haystack
I have the following models: 我有以下型号:
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)
and the following in search_indexes.py
: 以及
search_indexes.py
的以下内容:
class NoteIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True)
topic = indexes.CharField(model_attr='topic')
What I want to see in my template is: 我想在模板中看到的是:
Search for: <topic>
Results:
<ul>
<topic> <topic.user.username> <topic.user.referral_rcvd.filter(about=topic)
</ul>
Working in shell so it's easier, this gives me what I want: 在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()]
But this doesn't work in the html template: 但这在html模板中不起作用:
{% for result in object_list %}
{{ result.object.user.referral_rcvd.filter(about=i.object.topic).count() }}
{% endfor %}
If it works in the shell, how do I make it work in the template? 如果它在外壳中有效,如何在模板中使其有效? Thanks!
谢谢!
Finally solved it! 终于解决了! What I did was to use the
prepare_FOO
method: 我所做的是使用
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()
Then I ran python manage.py update_index
and placed the following in my template: 然后,我运行
python manage.py update_index
并将以下内容放入模板中:
{% for result in object_list %}
{{ result.referral }}
{% endfor %}
It's not result.object.referral
since we're referring to something in the index. 它不是
result.object.referral
因为我们要引用索引中的某些内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.