I would like to calculate the total balance of clients, i did this class with def but it calculate for one client only, i would like to create one def to calculate the total of client_balance of all clients i have.
class ClientsBalance(models.Model):
client = models.OneToOneField(Client, on_delete=models.CASCADE,related_name='Client')
def sales(self):
invoices = self.client.invoice_set.all()
sales_amount = 0
for invoice in invoices:
sales_amount += invoice.amountDuettc()
return sales_amount
def clientpayment(self):
invoices = self.client.invoice_set.all()
clientpayment = 0
for invoice in invoices:
clientpayment += invoice.amount_paid()
return clientpayment
def client_balance(self):
items = self.client.invoice_set.all()
invoice_balance = 0
for item in items:
invoice_balance = (self.sales()) - (self.clientpayment()) + (item.client.initialBalance)
return invoice_balance
First of all, you have a typo in your function which makes each iteration overwriting invoice_balance.
This will return the sum as desired:
def client_balance(self):
items = self.client.invoice_set.all()
invoice_balance = 0
for item in items:
invoice_balance += (self.sales()) - (self.clientpayment()) + (item.client.initialBalance)
return invoice_balance
Second of all you could merge your logic if required since you always use the same queryset like so e.g.:
def calculations(self):
queryset = self.client.invoice_set.all()
sales_amount = 0
clientpayment = 0
invoice_balance = 0
for client in queryset:
sales_amount += client.amountDuettc()
clientpayment += client.amount_paid()
invoice_balance += client.amountDuettc() - client.clientpayment() + client.client.initialBalance()
context = {
'sales_amount': sales_amount,
'clientpayment': clientpayment,
'invoice_balance': invoice_balance
}
return context
You current logic is returning balance of last client. In every iteration, invoice_balance override the previous value.
Try this.
Initialize an empty dictionary and append dictionary in every iteration:
def client_balance(self):
items = self.client.invoice_set.all()
invoice_dict = {}
for item in items:
invoice_balance = (self.sales()) - (self.clientpayment()) + (item.client.initialBalance)
invoice_dict[client_pk] = invoice_balance # client_pk is something unique for client.
return invoice_dict
This will return an dictionary with invoice balance of every client.
Related
here is my sanerio:
i have a model named Order:
i have some fields like that:
#hybrid_property
def final_total(self):
total = self.subtotal
if self.final_discount_amount is not None:
total -= self.final_discount_amount
if self.final_tax_cost is not None:
total += self.final_tax_cost
if self.final_tip is not None:
total += self.final_tip
if self.service_fee is not None:
total += self.service_fee
return total
#final_total.expression
def final_total(cls):
return func.sum(cls.final_total).label("final_total")
i want to get final_total of a record from database using query obj.
here is my query:
session.query(Order.final_total).filter_by(order.id=1).first()
i am getting error like:
python3.8/site-packages/sqlalchemy/ext/hybrid.py", line 1090, in _expr
return ExprComparator(cls, expr(cls), self)
RecursionError: maximum recursion depth exceeded
It is possible to do it using hybrid_property but you can face huge performance problem because this final_total calculation will have to be done during query runtime...
Better option is to add new column final_total to you model (and db) and make this calculation when any of elements (e.g. final_tip, etc.) is changed and the result save in this new column.
However, if hybrid property performance is enough for you, this is implementation that should work:
from sqlalchemy import func
#hybrid_property
def final_total(self):
total = self.subtotal
if self.final_discount_amount is not None:
total -= self.final_discount_amount
if self.final_tax_cost is not None:
total += self.final_tax_cost
if self.final_tip is not None:
total += self.final_tip
if self.service_fee is not None:
total += self.service_fee
return total
#final_total.expression
def final_total(cls):
return (
cls.subtotal +
func.coalesce(cls.final_discount_amount, 0) +
func.coalesce(cls.service_fee, 0) +
func.coalesce(cls.final_tax_cost, 0) +
func.coalesce(cls.final_tip, 0)
)
While trying to execute the code below to access the wallet
balance in the blockchain, I'm getting the error:
TypeError: slice indices must be integers or None or have an index method
This is the code I use:
class Blockchain:
def __init__(self):
self.chain = [] #stores the blockchain
self.transactions = ["Plain as vanilla"]
self.create_block(proof = 1, previous_hash="0") #helps with block creation
self.nodes = set()
def create_block(self, proof, previous_hash):
""" Used to make a block """
block = {
'index': len(self.chain) + 1,
'timestamp': str(datetime.datetime.utcnow()),
'proof': proof,
'previous_hash': previous_hash,
'data': self.transactions
}
self.transactions = []
self.chain.append(block)
return block
self.balance = 0
chain = Blockchain.chain[]
i = 0
for x in range(len(chain)):
if chain[i:"data":"reciver"] or chain[i:"data":"sender"] == publickey:
io = 0
for chain[i:"data":"reciver"] in chain[i:"data"]: #loop for iterating through the dictionary
amount = int(chain[io:"data":"amount"])
self.balance = self.balance + amount
io = io + 1
if chain[i:"data":"sender"] == publickey:
amount = int(chain[i:"data":"amount"])
self.balance = self.balance - amount
i = i + 1
if chain[-1] == 0:
self.balance = 0
return self.balance
the code is supposed to iterate through a dictionary inside a dictionary inside a list to find the balance of a wallet inside a blockchain, edit: I added the method of how a block is structured on the chain
Can you provide the error message?
I see that you instantiate "chain" as an empty list and then loops over it.
But assuming that you're only showing that the variable exists, to access a dictionary, nested inside a second dictionary within this list you should use:
chain[i]["data"]["receiver"]
I have to set the total_cost variable to be equal to the subtotal variable or the from the product class. However, when I try to derive the value from the class. It gives me an attribute error of AttributeError: 'Product' object has no attribute '_Product__total_price'. I am implementing where you apply the promo code then it will deduct the total price from the cart.
This is init.py and functions used.
#app.route('/applyPromo/<string:id>/', methods=['GET','POST'])
def apply_promo(id):
promotions_dict = {}
db = shelve.open('promotions.db','w')
promotions_dict = db['Promotions']
total_cost = 100
hidden = True
applied = True
click = True
get_from_class = False
print(promotions_dict)
promotions = promotions_dict.get(UUID(id))
db = shelve.open('storage.db', 'r')
product_dict = db['products']
for key in product_dict:
product = product_dict[key]
total_cost = product.get_total_price()
print(total_cost)
#when user apply promo, promo will get deleted from the list/dictionary of promos they have.
if promotions["type"] == 1:
total_cost = total_cost - 10
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 2:
total_cost = total_cost - 5
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 3:
total_cost = (70/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 4:
total_cost = (80/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
elif promotions["type"] == 5:
total_cost = (85/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
else:
total_cost = (90/100)*total_cost
hidden = False
print(f"Total Cost : {total_cost}")
promotions_dict.pop(UUID(id))
db['Promotions'] = promotions_dict
db.close()
db.close()
print(promotions_dict)
session['promotion_applied'] = promotions["id"]
return render_template("generatePromo.html", total_cost=total_cost,applied=applied, promotions_dict=promotions_dict,hidden=hidden,promotions=promotions,get_from_class=get_from_class, click=click)
#app.route('/shopping_cart')
def shopping_cart():
# session.clear()
error = None
cart_items = []
quantity_list = []
subtotal = 0
db = shelve.open('storage.db', 'r')
product_dict = db['products']
db.close()
for products in session:
item = product_dict.get(products)
cart_items.append(item)
if None in cart_items:
cart_items.remove(None)
quantity_list.append(session[products])
if products in quantity_list:
quantity_list.remove(products)
for i in range(len(cart_items)):
cart_items[i].set_purchased_quantity(quantity_list[i])
# set total price for single item
item_total = int(cart_items[i].get_price()) * int(cart_items[i].get_purchased_quantity())
cart_items[i].set_total_price(item_total)
# set total price of all items in cart
subtotal += item_total
print('QTY LIST', quantity_list)
print('CART', cart_items)
if not cart_items:
error = "Cart Is Empty"
return render_template('shoppingcart.html', products_list=cart_items, error=error, subtotal=subtotal)
This is the product class.
from uuid import uuid4
class Product:
def __init__(self, name, price, quantity, color, vase, remarks):
self.__product__id = str(uuid4())
self.__name = name
self.__price = price
self.__quantity = quantity
self.__color = color
self.__vase = vase
self.__remarks = remarks
self.__purchased_quantity = 0
self.__total_price = 0
def get_product_id(self):
return self.__product__id
def get_name(self):
return self.__name
def get_price(self):
return self.__price
def get_quantity(self):
return self.__quantity
def get_color(self):
return self.__color
def get_vase(self):
return self.__vase
def get_remarks(self):
return self.__remarks
def get_image(self):
return self.__image
def get_purchased_quantity(self):
return self.__purchased_quantity
def get_total_price(self):
return self.__total_price
def set_name(self, name):
self.__name = name
def set_price(self, price):
self.__price = price
def set_quantity(self, quantity):
self.__quantity = quantity
def set_color(self, color):
self.__color = color
def set_vase(self, vase):
self.__vase = vase
def set_remarks(self, remarks):
self.__remarks = remarks
def set_image(self, image):
self.__image = image
def set_purchased_quantity(self, purchased_quantity):
self.__purchased_quantity = purchased_quantity
def set_total_price(self, total_price):
self.__total_price = total_price
This is the traceback for the error.
Traceback
Leading double underscores should not be used as you are using them to define attributes of your class - single underscores is conventional. The problem with using leading double underscores is that the interpreter "mangles" the names of those attributes to avoid a subtle problem with inheritance, but leading to the problem, I believe, you are seeing. Here is a good read on the subject.
I have a function in my item ordering system where the goal is to keep totals of how many items were ordered and print each item and the amount they were ordered
class Totals(object):
def __init__(self, total):
self.total = total
def total(order_amount, coffee_id):
count = 0
print("Coffee Type\t\tAmount of Times ordered")
print("-----------\t\t-----------------------")
for coffee in coffee_available:
if coffee.coffee_id == coffee_id:
count = order_amount
coffee_id = order_coffee
print("{}\t- - -\t {} ".format(coffee.coffee_type, count))
With this I can only print one item and it does show how many of that item is ordered but again it only does this to one item
The function is based on user input and the items are
coffee_available=[Coffee(1, "1: Flat White", 3.50),
Coffee(2, "2: Long Black", 3.50),
Coffee(3, "3: Cappuccino", 4.00),
Coffee(4, "4: Espresso", 3.25),
Coffee(5, "5: Latte", 3.50)]
how do I change the function so that it prints all items and keeps track of the amount of items ordered each time it is called so that after my code is looped through multiple times it still displays each item and the amount of times it was ordered
Ok now I have a method that prints each of the types of coffee but prints the amount of coffee ordered for 1 item to all of the items and it does not retain the amount of coffee ordered for each item as is needed
class Order(object):
def __init__(self):
self.total = {}
def order(self, order_amount, coffee_id):
if coffee_id not in self.total.keys():
self.total[coffee_id] = 0
self.total[coffee_id] += order_amount
def print_order(self, coffee_id):
print(" ")
print("Coffee Type\t\tAmount of Times ordered")
print("-----------\t\t-----------------------")
for coffee in coffee_available:
print("{}\t- - -\t {} ".format(coffee.coffee_type, self.total[coffee_id]))
and this is how I call it
new_order = Order()
new_order.order(order_amount, coffee_available[order_coffee - 1])
new_order.print_order(coffee_available[order_coffee - 1])
any suggestions would be great
You should save a dictionary that map from the coffee id to it amount of orders and update it on each order.
class Totals(object):
def __init__(self):
self.total = {}
def order(self, order_amount, coffee_id):
if coffee_id not in self.total.keys():
self.total[coffee_id] = 0
self.total[coffee_id] += order_amount
For the printing you should add a print function that print self.total as you wish.
This is personally how I believe you should manage the items ordered. This example has a dictionary mapping a Coffee object to the number of times it was ordered.
class Order(object):
ID = 0
def __init__(self):
self._orders = {}
self._order_id = Order.ID
Order.ID += 1
def add_item(self, coffee):
# Gets the current quantity for the coffee
# If no previous order qty defaults to 1
qty = self._orders.get(coffee, 1)
# Add / update dict with coffee object and qty
self._orders[coffee] = qty
def display_order(self):
print("Coffee Type\t\tAmount of Times ordered")
print("-----------\t\t-----------------------")
# For each coffee object ordered | sorted by coffee id
for coffee in sorted(self._orders, key = lambda item: item.coffee_id):
print("{:<10}\t- - -\t {} ".format(coffee.coffee_type,
coffee.price * self._orders[coffee]))
I am studying for my final and this was a quiz question I missed. I need most of the help on the getTotal method. I need to loop through the list, find the price of each item, add the price to the total and return the total. I struggle with loops and I am not sure how to pull the second item out of a list.. [1] ?? I have tried many ways and am getting frustrated.
If there is anyone up that is willing to help me that would be great. I am still learning and am new at this so go easy on me, but I really want to learn it. It's probably not as hard as I make it out to be, but Ill be waiting for some input. Thank you!
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
def getPrice(self):
return self.price
def getName(self):
return self.name
class Cart:
def __init__(self, list):
self.list = []
def addItem(self, item):
self.list.append(self.list)
def getTotal(self):
total = 0
for item in self.list:
name, price = item # or price = item[1]
total = total + price
def getNumItems(self):
count = 0
for c in range(self.list):
count = self.list + 1
return count
def removeItem(self, item)
#removes the item from the cart's item list
def main():
item1 = Item("Banana", .69)
item2 = Item("Eggs", 2.39)
item3 = Item("Donut", .99)
c = Cart()
c.addItem(item1)
c.addItem(item2)
c.addItem(item3)
print "You have %i items in your cart for a total of $%.02f" %(c.getNumItems(), c.getTotal())
c.removeItem(item3)
print "You have %i items in your cart for a total of $%.02f" % (c.getNumItems(), c.getTotal())
main()
Here gives the time and I changed the code and now it is fully functional shopping cart
class Item(object):
def __init__(self, unq_id, name, price, qty):
self.unq_id = unq_id
self.product_name = name
self.price = price
self.qty = qty
class Cart(object):
def __init__(self):
self.content = dict()
def update(self, item):
if item.unq_id not in self.content:
self.content.update({item.unq_id: item})
return
for k, v in self.content.get(item.unq_id).iteritems():
if k == 'unq_id':
continue
elif k == 'qty':
total_qty = v.qty + item.qty
if total_qty:
v.qty = total_qty
continue
self.remove_item(k)
else:
v[k] = item[k]
def get_total(self):
return sum([v.price * v.qty for _, v in self.content.iteritems()])
def get_num_items(self):
return sum([v.qty for _, v in self.content.iteritems()])
def remove_item(self, key):
self.content.pop(key)
if __name__ == '__main__':
item1 = Item(1, "Banana", 1., 1)
item2 = Item(2, "Eggs", 1., 2)
item3 = Item(3, "Donut", 1., 5)
cart = Cart()
cart.update(item1)
cart.update(item2)
cart.update(item3)
print "You have %i items in your cart for a total of $%.02f" % (cart.get_num_items(), cart.get_total())
cart.remove_item(1)
print "You have %i items in your cart for a total of $%.02f" % (cart.get_num_items(), cart.get_total())
And a output is:
You have 8 items in your cart for a total of $8.00
You have 7 items in your cart for a total of $7.00
for getTotal:
def getTotal(self):
total = 0
for item in self.list:
name, price = item # or price = item[1]
total = total + price
BTW, Your addItem and getNumItems method are also wrong. Since it is final, you should try to understand what you are working on.