0

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 Subjects 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?

John Smith
  • 843
  • 2
  • 9
  • 21

1 Answers1

0

Try using the getattr() function. See Python string to attribute. You could dynamically pass the attribute you want to the same function. I haven't tested the below code, but I believe it'll put you on the right track.

def prepare_first_subject_name(self, obj, obj_attribute):
    first_subject_enrolled = Subject.objects.filter(student=obj).order_by('id')
    return getattr(first_subject_enrolled, obj_attribute)
Community
  • 1
  • 1
aberger
  • 2,299
  • 4
  • 17
  • 29