def optimize(qs, info_dict, field_map):
    """Add either select_related or prefetch_related to fields of the qs"""
    fields = collect_fields(info_dict)
    for field in fields:
        if field in field_map:
            field_name, opt = field_map[field]
            qs = (qs.prefetch_related(field_name)
                  if opt == "prefetch" else qs.select_related(field_name))

    return qs
Add either select_related or prefetch_related to fields of the qs