简体   繁体   中英

Append value to object using list comprehension

I am using django and due to some limitations of Django framework had to use list comprehension to filter values in my model.

My current statement is following

 po_list = [n for n in Material.objects.all() if ((F('total_inventory') + F('total_po') - F('total_so')) < F('min_quantity'))]

What I want to achieve is not just to return the filtered list but also to add a new column to n that will include the calculated values. (I don't want to redo those calculations again in template the goal is to have calculation done in one place only)

So it should be something like this

   po_list = [n+[F(max_quantity) - total_inv] for n in Material.objects.all()  deficit = (F('total_inventory') + F('total_po') - F('total_so')) total_inv = (F('total_inventory') + F('total_po') - F('total_so')) if (total_inv < F('min_quantity'))]

I struggle with 3 things

  • 1-Is it possible
  • 2-Sintaxis- how to code it correctly
  • 3-if it is possible how I name the new field I added to object - I need to access it somehow in the template

You shouldn't try to do this with a list comprehension. What your looking for is database aggregation. Django supports this to some extent. Some more information can be found in the docs: https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#values

You should add a values call to the queryset which contains the fields you want to group by. After that add an annotate to perform the required aggregation per grouped set of objects.

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