Home > Back-end >  How to make creating an array with using two models more efficient?
How to make creating an array with using two models more efficient?

Time:08-14

I want to create an array for a specific need. I have some parameters and I call a model (ProcessType) with this and filter the model with them. After that, I call another model with a time filter and I have to choose the objects that have the same case_type (string) name as the ProcessType. I created a function for that but it's very slow. How can I make it more efficient?

def case_groups(self, date_1, date_2, process_group):
    cases = Case.objects.filter(date_created__range=[date_1, date_2])
    process_types = ProcessType.objects.filter(reporting_group__option=process_group)
    report_group = []
    for i in cases:
        for j in process_types:
            if j == i.case_type:
                report_group.append(i)
    print(report_group)
    return report_group

CodePudding user response:

You can do this:

report_group = [
    i 
    for i in cases
    for j in process_types
    if j == i.case_type
]

Or better:

Case.objects.filter(
     date_created__range=[date_1, date_2],
     case_type__in=ProcessType.objects.filter(
         reporting_group__option=process_group
     )
)

Or if the models has a ForeginKey:

Case.objects.filter(
     date_created__range=[date_1, date_2],
     case_type__reporting_group__option=process_group
)
  • Related