0

블로그 게시물이 있는데 검색 색인에 주석을 추가하려고하는데 어떤 이유로 작동하지 않습니다 ... 내 의견에 일반 외래 키가있는 경우 문제. 알아두기, 그것은 태그에 대해 작동합니다. 건초 더미 - 준비된 필드가있는 개체를 찾을 수 없습니다.

class BlogIndex(indexes.SearchIndex, indexes.Indexable): 
    text = indexes.CharField(document=True, use_template=True) 
    headline = indexes.CharField(model_attr="headline", null=True) 
    body = indexes.CharField(model_attr="body") 
    date = indexes.DateTimeField(model_attr='date') 
    mytags = indexes.MultiValueField() 
    mycomments = indexes.MultiValueField() 

    def prepare_mytags(self, obj): 
     return [tag.name for tag in obj.tags.all()] 

    def prepare_mycomments(self, obj): 
     cur_model = ContentType.objects.get_for_model(obj) 
     cur_comments = Comment.objects.filter(content_type=cur_model, object_pk=obj.id) 
     return [str(cur_c.content) for cur_c in cur_comments] 

    def get_model(self): 
     return Snip 

    def index_queryset(self, using=None): 
     """Used when the entire index for model is updated.""" 
     return self.get_model().objects.filter(date__lte=timezone.now()) 

내 템플릿 : 그것은 중요한 경우

{{ object.headline }} 
{{ object.body }} 
{% for c in object.mycomments %}{{ c }} {% endfor %} 
{% for tag in object.tags.all %}{{ tag.name }} {% endfor %} 

나는 또한 DRF-건초 더미를 사용하고 있는데, 이것은 시리얼입니다 :

class BlogSearchSerializer(HaystackSerializer): 
    class Meta: 
     index_classes = [BlogIndex] 

     fields = [ 
      "headline", "body", "date", "mytags", 'mycomments', "content", 
     ] 

내가 함께 찾고 있어요 content = XX 주석에서 아무것도 찾을 수 없습니다.

내가 뭘 잘못하고 있니?

감사 R

답변

0

귀하의 템플릿이 잘못 - 특히 당신이하고있다 :이 경우

{% for c in object.mycomments %}{{ c }} {% endfor %} 

objectBlog의 인스턴스가 아닌 BlogIndex의 인스턴스입니다. 템플릿 엔진은 그런 것을 찾지 못할 것이고 아무것도하지 않을 것입니다. 당신은 아마 대신이 작업을 수행 할 수 :

{% for c in object.comment_set.all %}{{ c }}{% endfor %} 

는 의견들이 부착되어있는 Blog 항목에 대한 외래 키를 가지고 있다고 가정.

BlogIndex.mycomments에서 실제로 색인을 생성 할 필요는 없습니다 (예 : 필터링/패싯).

+0

문제는 주석의 외래 키가 일반 외래 키이므로 comment_set AFAK을 사용할 수 없습니다. 감사! – Rani

+0

나는 일종의 그것을 고쳤지만 완전히. 내 블로그 모델에'comments = GenericRelation (Comment)'을 추가했는데 이제 색인을 생성하고 /? content = XX를 사용하여 검색 할 수 있지만 주석 만 검색 할 수는 없으며 결과에 주석을 표시 할 수 없습니다. drf-haystack을 사용합니다. – Rani

+0

'Blog' 모델에 메소드를 추가 할 수 있습니다 (예 :'get_comments'). 현재'BlogIndex.prepare_mycomments'에있는 로직을 수행하고 일련의 주석을 리턴합니다. 그런 다음'object.get_comments'를 사용하여 템플릿에서 액세스 할 수 있습니다. – solarissmoke