用hays对相关对象进行索引和检索

2024-05-16 22:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我对搜索实现还很陌生,在我学习的过程中请耐心等待!在

所以我的宠物项目是一个配方网站,每个配方可以有n个步骤。模型看起来像:

class Recipe(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    hotness = models.ForeignKey(Hotness)
    recipe_diet = models.ManyToManyField(DietType)
    ingredients = models.ManyToManyField(Ingredient, through="RecipeIngredient")

class DietType(models.Model):
    diet_type = models.CharField(max_length=50)
    description = models.TextField(null=True, blank=True)

class RecipeIngredient(models.Model):
    recipe = models.ForeignKey(Recipe)
    ingredient = models.ForeignKey(Ingredient)
    quantifier = models.ForeignKey(Quantifier)
    quantity = models.FloatField()

class RecipeSteps(models.Model):
    step_number = models.IntegerField()
    description = models.TextField()
    recipe = models.ForeignKey(Recipe)

(简称为简洁)

我想索引所有的:食谱,食材,饮食类型和步骤。。。 饮食类型和受试者似乎工作得很好,但步骤却并非如此。我想这和'RelatedSearchQuerySet'的用法有关?在

这是我的搜索_索引.py公司名称:

^{pr2}$

这是模板配方_文本.txt公司名称:

{{ object.title }}
{{ object.cuisine }}
{% for ingr in object.ingredients.all %}
  {{ ingr.title }}
{% endfor %}
{{ object.description }}
{% for dt in object.recipe_diet.all %}
  {{ dt.diet_type }}
{% endfor %}
{{ object.user }}
{{ object.hotness }}
{% for step in object.recipesteps.all %}
  {{ step.description }}
{% endfor %}
{{ object.body }}

我可以搜索配料,标题,描述,饮食类型-一切正常,除了食谱步骤。在

最后,我现在只通过shell进行查询:

#producing results:
sq = SearchQuerySet().filter(content='onion') #ingredient
sq = SearchQuerySet().filter(content='bolognese') #title
sq = SearchQuerySet().filter(content='bologna') #description
#not producing any results:
sq = SearchQuerySet().filter(content='chop') #step
sq = RelatedSearchQuerySet().filter(content='chop').load_all() #assuming this does the expanded search

有什么想法吗?在


Tags: modelobjecttitlemodelsstepsqrecipe步骤
1条回答
网友
1楼 · 发布于 2024-05-16 22:21:10

我发现了两个问题:

  1. 你的RecipeIndex中的名称prepare_steps是错误的,应该是prepare_{field_name},所以把它改成prepare_recipesteps

  2. 您试图以错误的方式访问相关步骤object.recipesteps.all对象{},它应该是object.recipesteps_set.all。或者继续使用recipesteps,但将其作为RecipeSteps模型中的RecipeSteps添加到ForeignKey配方中,例如

    class RecipeSteps(models.Model):
        # //
        recipe = models.ForeignKey(Recipe, related_name='recipesteps')
    

相关问题 更多 >