django-haystack / django-haystack/django-haystack

What is the best way to add fields dynamically to my SearchIndex?

Open
#1,764 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
3.7k
Forks
1.3k
Avg merge
3h 18m
Merged PRs (30d)
3

Description

Currently i see two possibilities, with using locals() and using setattr() after definition of SearchIndex class:

1.

class JobTestIndex(indexes.SearchIndex, indexes.Indexable):
    for name in fields:
	locals()["attr_%s" % name] = DescriptionSearchField(boost=3, **{"d_attr": name, "name": "attr"})
	locals()["slug_%s" % name] = DescriptionSearchField(**{"d_attr": name, "name": "slug"})

2.

class JobTestIndex(indexes.SearchIndex, indexes.Indexable):
    pass

for name in fields:
    setattr(JobTestIndex, "attr_%s" % name, DescriptionSearchField(boost=3, **{"d_attr": name, "name": "attr"}))
    lsetattr(JobTestIndex, "slug_%s" % name, DescriptionSearchField(**{"d_attr": name, "name": "slug"}))

What is then the correct solution for my issue?

Any suggestions are greatly appreciated. Thanks.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No project file or test is named. Start with the SearchIndex and DescriptionSearchField usage shown in the issue, then inspect how django-haystack registers fields declared in a class versus fields added afterward. Done would require a decided, documented approach with tests demonstrating dynamic fields.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
backend, search
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.