简体   繁体   中英

Preventing code duplication in Elastic Search

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM