How can I add "%" next to value in tree view column for below field:
rec.reserved_qty_per = round(rec.sum_reserved_qty / rec.sum_dmd_qty * 100)
when I used to add (+ "%") it's giving me an error that can't mix between float and str fields.
Here's is my Code:
sum_dmd_qty = fields.Float(compute='calculate_dmd_qty', string='Total Ordered Quantity', digits=(12,0))
sum_reserved_qty = fields.Float(compute='calculate_reserved_qty', string='Total Ready Quantity', digits=(12,0))
reserved_qty_per = fields.Float(compute='_compute_percentage', string='Ready (%)', digits=(12,0))
#api.depends('sum_reserved_qty', 'sum_dmd_qty')
def _compute_percentage(self):
for rec in self:
if rec.sum_dmd_qty:
rec.reserved_qty_per = round(rec.sum_reserved_qty / rec.sum_dmd_qty * 100)
The easiest one is to change reserved_qty_per to a Char field.
reserved_qty_per_chr = fields.Char(compute='_compute_percentage', string='Ready (%)')
#api.depends('sum_reserved_qty', 'sum_dmd_qty')
def _compute_percentage(self):
for rec in self:
if rec.sum_dmd_qty:
qty = round(rec.sum_reserved_qty / rec.sum_dmd_qty * 100)
rec.reserved_qty_per = "{0} {1}".format(qty,"%")
Related
I'm trying to set stay column field value in TestLocation model table as stay or on_move by calculating difference between lat and longs using for loop to iterate between rows of model table and if condition where to set value of stay field as stay or on_move which depends on difference as shown in views.py.
below is my model.py:
class TestLocation(models.Model):
LOCATOR_YES_NO_CHOICES = ((None, ""), (True, "Yes"), (False, "No"))
longitude = models.FloatField()
latitude = models.FloatField()
processed = models.BooleanField(
choices=LOCATOR_YES_NO_CHOICES,
max_length=3,
blank=True,
null=True,
default=None,
)
stay=models.CharField(max_length=100,null=True)
duration=models.FloatField(null=True)
and views.py funtion to set value of stay field in above model:
def mark_stay_location():
if TestLocation.objects.filter(processed=None):
k = TestLocation.objects.filter(processed=None).order_by("timestamp")
p = len(k)
# list_lat1 = []
# list_lat2 = []
# list_long1 = []
# list_long2 = []
for i in range(p - 1):
rowpairs = k[i : i + 2]
lat1 = rowpairs[0].latitude
# list_lat1.append(lat1)
lat2 = rowpairs[1].latitude
# list_lat2.append(lat2)
long1 = rowpairs[0].longitude
# list_long1.append(long1)
long2 = rowpairs[1].longitude
# list_long2.append(long2)
lat = abs(lat2 - lat1)
long = abs(long2 - long1)
a = sin(lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(long / 2) ** 2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
for rowpair in rowpairs:
row_id = rowpair.id
po = TestLocation.objects.filter(id=row_id)
if lat < 0.0009 or long < 0.0009:
po.update(stay="stay")
po.update(processed=True)
else:
po.update(stay="on_move")
po.update(processed=True)
duration()
return Response(status=status.HTTP_200_OK)
and if the stay field has values in list format["stay","stay","stay","on_move","on_move","on_move"] then using timestamp(154653268 value for example ) of respective row ,I need to calculate duration between first and last stay value and again between next first on_move and last one.I took that list as example ,it maybe like this["stay","on_move","stay","on_move","stay","on_move"].
i have price model
class Product(models.Model):
price = models.IntegerField
membership_discount = models.DecimalField
if i get price parameter, (ex. min_price = 100000, max_price = 500000)
I want to get the products multiplied by the price fields and membership_discount fields.
not this
Product.objects.filter(price__range = (min_price, max_price))
i want
Product.objects.filter(price * (1+membership_discount)__range = (min_price, max_price))
lte = less than or equal to
gte = greater than or equal to
this is documentation: https://docs.djangoproject.com/en/4.0/ref/models/querysets/#gt
max_price = #max price logic here
min_price = #min price logic her
#this will filter all products (price <= max_price and price >= min_price)
Product.objects.filter(price__lte = max_price, price__gte = min_price)
You could use annotations for the QuerySet and apply the filter on the annotation.
Product.objects.annotate(
member_price=F('price') * (1 + F('membership_discount'))
).filter(
member_price__range=(min_price, max_price)
)
If the pricefield and the membership_dicsount do not have the same type, you might need to make usage of the ExpressionWrapper with a specific output_field
Product.objects.annotate(
member_price=ExpressionWrapper(
F('price') * (1 + F('membership_discount')),
output_field=DecimalField()
)
).filter(
member_price__range=(min_price, max_price)
)
Docs:
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.query.QuerySet.annotate
https://docs.djangoproject.com/en/4.0/topics/db/aggregation/
https://docs.djangoproject.com/en/4.0/ref/models/expressions/#using-f-with-annotations
I am trying to create a dropdown with ipywidgets, it needs to return a variable value, this variable value may change depending on other slider input values. When I try to return the variable I get the error: NameError: 'adjustment_one' Not Defined.
calculated_area = input_slider / numstorey_input_slider * 0.7
revised_area = input_slider - calculated_area
adjustment_one = revised_area / input_slider
location = ipywidgets.Dropdown(
options=[('Internal', 1), ('Roof', adjustment_one), ('External', 2) ],
value=1,
description='Plant Space Location: ',
)
The above method is solved and was an indenting error however I have now found that I can't pass a float value using the ipywidget dropdown. Below is the code - based on what is selected in the drop down this will be mapped to a dataframe as a multiplier. However when I open the excel document it only every returns the value '0'. This value should actually be 0.87 when Roof is selected, and will change depending on slider input values.
calculated_roof_area = gia_input_slider / numstoreys_input_slider * 0.7
revised_gia_roofinput = gia_input_slider - calculated_roof_area
gia_adjustment_rooftop = revised_gia_roofinput / gia_input_slider
plantspace = ipywidgets.Dropdown(
options=[('Internal', 1), ('Roof', gia_adjustment_rooftop), ('External', 2) ],
value=1,
description='Plant Space Location: ',
)
print(plantspace)
df = pd.read_excel(r'dataframe_final.xlsx', sheet_name='sheet1')
# below recalculates the adjusted qty when the slider position changes
multipliers = {
'Building Footprint Factor': bldg_footprint_factor,
'CAT A Fitout Yes / No': fitout_cat_dropdown,
'GIA Factor': gia_factor,
'GIA Adjustment - Rooftop': plantspace_dropdown
}
df['QP1 Multiplier'] = df['QP1'].map(multipliers)
df['QP2 Multiplier'] = df['QP2'].map(multipliers)
df['QP3 Multiplier'] = df['QP3'].map(multipliers)
df['QP4 Multiplier'] = df['QP4'].map(multipliers)
df['QP5 Multiplier'] = df['QP5'].map(multipliers)
df['QP6 Multiplier'] = df['QP6'].map(multipliers)
df['QP7 Multiplier'] = df['QP7'].map(multipliers)
df['QP8 Multiplier'] = df['QP8'].map(multipliers)
df['QP9 Multiplier'] = df['QP9'].map(multipliers)
Can anybody help?
I am trying to obtain the sum of the return values obtained from the expenses_calc function, but I am facing "TypeError: 'float' object is not iterable". What changes do I need to make to solve this error?
from nsetools import Nse
nse = Nse()
#Name of stocks and buy prices
stocks = {
"APLAPOLLO": 878.2,
"AVANTIFEED": 488.95,
"BALAMINES": 308.95
}
#Quantity of stocks
qty = {
"APLAPOLLO": 10,
"AVANTIFEED": 10,
"BALAMINES": 10
}
def get_closing(stock):
"""
Function to obtain closePrice of stocks
"""
return nse.get_quote(stock)['buyPrice1']
def expenses_calc(buy,sell,qty):
"""
Function to calculate the applicable expenses
"""
stt = 0.10
ttc = 0.00325
service_tax = 15.0
sebi_charges = 0.0002
swacch_bharat_cess = 0.02
stamp_duty = 0.01
turnover = (buy * qty) + (sell * qty)
stt_total = (stt / 100) * turnover
total_tran_charge = (ttc / 100) * turnover
service_tax = (service_tax / 100) * total_tran_charge
sebi_charges = (sebi_charges / 100) * turnover
stamp_duty = (stamp_duty / 100) * turnover
total_tax_and_charges = stt_total + total_tran_charge + service_tax + sebi_charges + stamp_duty
total_investment = buy * qty
current_value = sell * qty
net_profit = (sell * qty) - (buy * qty) - total_tax_and_charges
return net_profit
#For loop that calls the expenses_calc function in a loop with the right arguments
for key in stocks.keys():
buy_price = stocks[key]
sell_price = get_closing(key)
stock_qty = qty[key]
expenses_func_call = expenses_calc(buy_price, sell_price, stock_qty)
print(sum(expenses_func_call))
The line where the type error occurs
print(sum(expenses_func_call))
I have tried creating an empty myresults list and then appending the return value of expenses_calc function to it then printing the sum of the list, which also doesn't work.
for key in stocks.keys():
myresults = []
buy_price = stocks[key]
sell_price = get_closing(key)
stock_qty = qty[key]
expenses_func_call = expenses_calc(buy_price, sell_price, stock_qty)
myresults.append(expenses_func_call)
print(sum(myresults))
In addition to the previous answer, you need to pass a list to the sum function, so your initial attempt to correct the problem is correct. But you should initialize the myresults list before entering the loop. Currently, each time you execute the loop, you are in effect overwriting the myresults content.
In your next attempt with appending values to the list myresults, your print statement should be outside the for loop
I have a product called "Coupon" with negative amount which is used to offset the product price. However, it seems like Odoo 8 does not allow computation of negative amount to price_subtotal (it becomes 0.00):
Coupon ... ... 1 Each -40.0000 0.0000
When I remove the negative sign, it computes
Coupon ... ... 1 Each 40.0000 40.0000
From an accounting perspective, the total invoice should not be negative. That stays true. However, I do need to allow negative computation of invoice line item(s). Where and what do I need to change? I tried looking into account/account.py but to no avail so far - it's all just "tax" related.
Thanks in advance!
Details of the amount column for the line total
class account_invoice(models.Model)
....
#api.one
#api.depends('invoice_line.price_subtotal', 'tax_line.amount')
def _compute_amount(self):
self.amount_untaxed = sum(line.price_subtotal for line in self.invoice_line)
self.amount_tax = sum(line.amount for line in self.tax_line)
self.amount_total = self.amount_untaxed + self.amount_tax
....
class account_invoice_line(models.Model):
_name = "account.invoice.line"
_description = "Invoice Line"
_order = "invoice_id,sequence,id"
#api.one
#api.depends('price_unit', 'discount', 'invoice_line_tax_id', 'quantity',
'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id')
def _compute_price(self):
price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
taxes = self.invoice_line_tax_id.compute_all(price, self.quantity, product=self.product_id, partner=self.invoice_id.partner_id)
self.price_subtotal = taxes['total']
if self.invoice_id:
self.price_subtotal = self.invoice_id.currency_id.round(self.price_subtotal)
#api.model
def _default_price_unit(self):
if not self._context.get('check_total'):
return 0
total = self._context['check_total']
for l in self._context.get('invoice_line', []):
if isinstance(l, (list, tuple)) and len(l) >= 3 and l[2]:
vals = l[2]
price = vals.get('price_unit', 0) * (1 - vals.get('discount', 0) / 100.0)
total = total - (price * vals.get('quantity'))
taxes = vals.get('invoice_line_tax_id')
if taxes and len(taxes[0]) >= 3 and taxes[0][2]:
taxes = self.env['account.tax'].browse(taxes[0][2])
tax_res = taxes.compute_all(price, vals.get('quantity'),
product=vals.get('product_id'), partner=self._context.get('partner_id'))
for tax in tax_res['taxes']:
total = total - tax['amount']
return total
Odoo's default behaviour is handling it as expected. The problem is custom code. (For more information read the questions comments)