Get total invoices per customer - mapreduce

I have a database where I have docs like customers (customerId, firstName, lastName, phoneNo, eMail) and invoice (invoiceId, invoiceDate, customerId).
I want to get the sum of invoices per customer in a view.
I'm currently using Fauxton 2.0.
My view is currently:
function (doc) {
if (doc.customerId && doc.invoiceId) {
emit(doc.customerId, doc.invoiceId);
}
}
But I want to add some sort of reduce function which can give me the total sum of invoices.
thanks.

Well, I solved the problem, it was just an issue of changing the reduce function _sum to _count, to get the total amount of invoices. So when requesting the key(customerId), I get the count.

Related

How to Count quantity of my QuerySet. Django

Well, i have the following function:
employees_birthday = Employees.objects.filter(EmployeeDataNasc__gte=first_day, EmployeeDataNasc__lte=last_day)
It serves to return employees born between the dates. She returns:
<QuerySet [<Employees: Alberto Santos>, <Employees: Josney Arman>]>
But, I would just like to display the number of employees in the QuerySet, i.e. make a Count function.
Can someone help me with the syntax?
If you are going to display the Employees anyway, then it is better to use len(…). This will fetch the Employees in memory, and return the number of Employees:
employees_birthday = Employees.objects.filter(
EmployeeDataNasc__range=(first_day, last_day)
)
number_of_birthdays = len(employee_birthdays)
if you however plan to only render the number of Employees, then you use .count() [Django-doc], since this will prevent fetching the items in memory.

Get instagram followers count at a given date

Is there a way to retrieve the amount of followers that an instagram business page has at a given date?
Looking inside the api, there is a field follower_count that returns the total number of new followers in each day within specified date range. But I want the total count, not the new ones.
If this information does not exists, how can I calculate it?

how to display different price for same product in opencart?

Want to display different prices for a same product. Multiple sellers will be selling the same product with their respective prices is what I want to display if someone views a product....
If I understand you, It's not a coding case.
1 - go to Admin/Sales/Customers/Customers Group, and create as many groups as you want.
2 - go to Admin/Catalog/Products and edit an exiting product or create a new product. in Special tab you can assign different prices for each group created on step 1.
My first thought is to make them separate products, however you might want to display a product on a single page with a list of sellers to choose from, in which case...
The different sellers are product options!
The way I have set this up is by adding fields for them in the SQL products table such as price_a, price_b, price_c and then adding another field to the customers table called price_category with the relevant prefix (A,B,C). Then I wrote a function under getProduct (catalog/model/catalog/product.php) to cater for this.
The reason I took this route is because my files are uploaded automatically to the table and links to another program which generates invoices and sends the result back to the website automatically.
My Function is as follows:
if ($query->rows) {
foreach ($query1->rows as $row) {
$price_category = strtolower($row['price_category']);
$debtor_class = $row['debtor_class'];
$price_percentage = $row['price_percentage'];
}
} else {
$price = ($query->row['discount'] ? $query->row['discount'] : $query->row['price']);
$special = $query->row['special'];
}
$product_special_query = $this->db->query("SELECT price, to_qty, bonus_qty FROM product_special WHERE debtor_class = '".$debtor_class."' AND product_id = '".(int)$product_id."' AND customer_group_id = '".(int)$customer_group_id. "'");

Django - show sums of a table of records

I have a table which has a list of invoices and their details:
class Invoice(models.Model):
invoiceNum = models.CharField(etc...)
invoiceDate = models.DateField(etc...)
customerID = models.ForeignKey(etc...)
isPaid = models.CharField(etc...)
The Invoice records do not hold the actual invoice total. Instead, an invoice's total is made up of several Invoice_Line_Item records, held in another table:
class Invoice_Line_Item(models.Model):
invNum = models.ForeignKey(Invoice)
itemName = models.CharField(etc...)
itemPrice = models.DecimalField(etc...)
I have a webapp that shows all the invoices in a big HTML table, along with all the details of that invoice on the table's tr row. Details such as, Invoice Date, Invoice Number, Customer ID, all come from that Invoice table. There are hundreds of invoices to display in this HTML table.
What I would like to do is also show each invoice's total value - which is the sum of all the line items. However, I can't think of a simple way to acomplish this since the invoice details and the line items that make up the invoice's total are in two different tables.
One way I thought is to pass the entire Invoice_Line_Item querySet into the HTML template, then for each invoice displayed in a table tr, I could iterate over the entire Invoice_Line_Item querySet, adding up all the line items that match the current invoice. This, however, seems hugely inefficient.
Any better ideas on how to do this?
Thanks!
One word: Aggregation
Invoice_Line_Item.objects.filter(invNum=invoice).aggregate(Sum('itemPrice'))
https://docs.djangoproject.com/en/dev/topics/db/aggregation/
Another way is to store the total in Invoice and update it whenever you change a related Invoice_Line_Item
One more word: annotate.
from django.models import Sum
Invoice.objects.filter( .. ).annotate( InvTotal=Sum( 'invoice_line_number__itemPrice' ) )
InvTolal becomes a new attribute of Invoice object, you can use it in template the same way as invoiceNum or invoiceDate.
With this approach you do not have to pass any additional data structures to your template, only a QuerySet of Invoices.
Please note:
Argument of Sum is a string, which is a concatenation of the name of related model converted to lowercase, than double '_', and than the name of a field in related model.

Django both filtered and total number of a certain field

I have such model and query
class Employer(Models.model)
name = ...
class JobTitle(Models.model)
name = ...
employer = models.ForeignKey(Employer)
and query is
Employer.objects.select_related('jobtitle')
.filter(jtt__activatedate__range=[startdate,enddate])
.annotate(jtt_count=Count('jobtitle'))
.order_by('-jtt_count')[:5]
As you see it returns 5 employer list which has maximum number of jobtitles which are related to that employer and whose activation date is in some certain range.
However, I also want to get the total number of jobtitles of each employer in that query.
Of course I may loop over each employer and make such query JobTitle.objects.filter(employer = emp) and taking length of that query but it is bad solution.
How can I achive this in that query?
Although it may not be possible to get both total number and filtered number of job titles, I may get the jobttiles of each emplyoer such that len(emp.jobtitle) however it also didn't work.
Thanks
Try the extra lookup. So, in your case it may be like this:
.extra(
select={
'jobtitle_count': 'SELECT COUNT(*) FROM YOURAPP_jobtitle WHERE YOURAPP_jobtitle.employer_id = YOURAPP_employer.id'
},
)