How do I avoid code duplication for the purposes of indexing in Elastic Search (Django Project)?
It is my understanding that you can't return objects in elastic search, but a lot of times I find myself using different variables from the same related object.
For example if I had an index for a Student
and needed Information about the Subject
s they're taking. If I wanted the first Subject
the student enrolled in, I would do something like this in elastic search:
...
first_subject_enrolled_id = indexes.IntegerField(model_attr='service__id')
def prepare_first_subject_enrolled_id(self, obj):
first_subject_enrolled = Subject.objects.filter(student=obj).order_by('id')
return first_subject_enrolled.id
But then let's say I also want the Subject
name of the first class enrolled. I would have to repeat a lot of code. For example:
def prepare_first_subject_name(self, obj):
first_subject_enrolled = Subject.objects.filter(student=obj).order_by('id')
return first_subject_enrolled.name
Is there a way I can just call the index function prepare_first_subject_enrolled_id to avoid duplication and unnecessary indexing of similar code?