For loop did't working in view.py Django? - python

in view.py
Id = [2,3,4,5,6,7,8]
for w in Id:
A = w
Pending = pending(A)
data = {
'Pending': Pending,
}
return render_to_response('dialer_campaign/campaign/list.html', data, context_instance=RequestContext(request))
def pending(campaign_id):
A = Campaign_phonebook.objects.values_list('phonebook_id').filter(campaign_id = campaign_id)
B = Contact.objects.filter(phonebook_id__in=A).count()
C = Subscriber.objects.filter(campaign_id = campaign_id).exclude(status = 1).count()
Result = B - C
return Result
When i add manual value instead of A it gives result,but now i want to give value by for loop it is not working.Why ? Can anybody Help me ?
Want changes should i do in templates ?
Thanks in Advance..

Take your data object in list and render to the template
Refer following code
Id = [2,3,4,5,6,7,8]
pending_list = []
for w in Id:
pending = pending(w)
pending_list.append({'pending': pending})
return render_to_response('dialer_campaign/campaign/list.html', pending_list, context_instance=RequestContext(request))
def pending(campaign_id):
A = Campaign_phonebook.objects.values_list('phonebook_id').filter(campaign_id = campaign_id)
B = Contact.objects.filter(phonebook_id__in=A).count()
C = Subscriber.objects.filter(campaign_id = campaign_id).exclude(status = 1).count()
Result = B - C
return Result
Use pending_list in your template. In pending_list list you get all the pending objects.

Related

Is there a way to avoid loops while instancing SQLAlchemy ORM objects?

I am currently using SQLAlchemy CORE to collect data from some heterogenous databases, run some calculations and then write the data in a new database using SQLAlchemy ORM model.
Here is the time breakdown:
Start -- 2022-06-27 13:53:50.967981
End B3DB Init -- 0:00:02.276641
End CORE Read -- 0:00:00.686167
End Calculations -- 0:00:00.577456
End DADODB Init -- 0:00:00.063829
End ORM Instancing -- 0:00:03.511613
End DADODB Commit -- 0:00:01.050192
Total -- 0:00:08.165898
The most time costly phase is looping through the 1K rows approximately of data to be inserted.
There are two tables and this is what I'm doing:
undrl_asset = Asset(
timestamp = datetime.now(),
tradedate = tgtdate,
trckrsymb = undrl_ticker,
openprice = undrl_data.iloc[0]['UNDRL_PREABE'],
maxprice = undrl_data.iloc[0]['UNDRL_PREMAX'],
minprice = undrl_data.iloc[0]['UNDRL_PREMIN'],
avgprice = undrl_data.iloc[0]['UNDRL_PREMED'],
lastprice = undrl_data.iloc[0]['UNDRL_PREULT'],
buyoffer = undrl_data.iloc[0]['UNDRL_PREOFC'],
selloffer = undrl_data.iloc[0]['UNDRL_PREOFV'],
numdeals = int(undrl_data.iloc[0]['UNDRL_TOTNEG']),
totamnt = int(undrl_data.iloc[0]['UNDRL_QUATOT']),
totcash = undrl_data.iloc[0]['UNDRL_VOLTOT'],
vh = pd.to_numeric(undrl_data.iloc[0]['UNDRL_VH'])
)
for i in range(num_calls):
this_option = Derivative(
timestamp = datetime.now(),
tradedate = tgtdate,
trckrsymb = call_raw_data.iloc[i]['OPT_TRCKR_SYMB'],
undrlasst = undrl_ticker,
sgmntname = call_raw_data.iloc[i]['OPT_SEGMENT'],
expirdate = call_raw_data.iloc[i]['OPT_EXP_DATE'],
exrcprice = call_raw_data.iloc[i]['OPT_STRIKE'],
optnstyle = str(call_raw_data.iloc[i]['OPT_STYLE'])[0:1],
mrktprice = call_raw_data.iloc[i]['OPT_PREULT'] if call_raw_data.iloc[i]['OPT_PREULT'] > 0 else None,
dayqntneg = call_raw_data.iloc[i]['OPT_VLMNEG'] if call_raw_data.iloc[i]['OPT_VLMNEG'] > 0 else None,
cvrdpos = int(call_raw_data.iloc[i]['OPT_COVERED']),
blkspos = int(call_raw_data.iloc[i]['OPT_BLOCKD']),
uncvpos = int(call_raw_data.iloc[i]['OPT_UNCOVRD']),
totlpos = int(call_raw_data.iloc[i]['OPT_TOT_OI']),
holdqty = int(call_raw_data.iloc[i]['OPT_TITULRS']),
writqty = int(call_raw_data.iloc[i]['OPT_LANCDRS']),
iq = call_raw_data.iloc[i]['OPT_TITULRS']/call_raw_data.iloc[i]['OPT_LANCDRS'],
timtoexp = call_raw_data.iloc[i]['CALC_TIME_TO_EXP'],
moneynes = call_raw_data.iloc[i]['CALC_MNYNS'],
impldvol = call_raw_data.iloc[i]['CALC_IV'] if call_raw_data.iloc[i]['CALC_IV'] > 0 else None,
polycofa = call_raw_data.iloc[i]['CALC_P_A'],
polycofb = call_raw_data.iloc[i]['CALC_P_B'],
polycofc = call_raw_data.iloc[i]['CALC_P_C'],
chosnvol = call_raw_data.iloc[i]['CALC_VOL'],
optdelta = call_raw_data.iloc[i]['CALC_DELTA'],
optgamma = call_raw_data.iloc[i]['CALC_GAMMA'],
optpctgm = call_raw_data.iloc[i]['CALC_PCT_GAMMA'],
opttheta = call_raw_data.iloc[i]['CALC_THETA'],
optbgt = call_raw_data.iloc[i]['CALC_BGT'] if call_raw_data.iloc[i]['CALC_BGT'] > 0 else None,
totdelta = int(call_raw_data.iloc[i]['TOT_DELTA']),
totgamma = int(call_raw_data.iloc[i]['TOT_GAMMA']),
ttpctgmm = int(call_raw_data.iloc[i]['TOT_PCT_GAMMA']),
tottheta = int(call_raw_data.iloc[i]['TOT_THETA']),
totbgt = int(call_raw_data.iloc[i]['TOT_BGT'])
)
options_array.append(this_option)
for i in range(num_puts):
this_option = Derivative(
timestamp = datetime.now(),
tradedate = tgtdate,
trckrsymb = put_raw_data.iloc[i]['OPT_TRCKR_SYMB'],
undrlasst = undrl_ticker,
sgmntname = put_raw_data.iloc[i]['OPT_SEGMENT'],
expirdate = put_raw_data.iloc[i]['OPT_EXP_DATE'],
exrcprice = put_raw_data.iloc[i]['OPT_STRIKE'],
mrktprice = put_raw_data.iloc[i]['OPT_PREULT'] if put_raw_data.iloc[i]['OPT_PREULT'] > 0 else None ,
dayqntneg = put_raw_data.iloc[i]['OPT_VLMNEG'] if put_raw_data.iloc[i]['OPT_VLMNEG'] > 0 else None ,
cvrdpos = int(put_raw_data.iloc[i]['OPT_COVERED']),
blkspos = int(put_raw_data.iloc[i]['OPT_BLOCKD']),
uncvpos = int(put_raw_data.iloc[i]['OPT_UNCOVRD']),
totlpos = int(put_raw_data.iloc[i]['OPT_TOT_OI']),
holdqty = int(put_raw_data.iloc[i]['OPT_TITULRS']),
writqty = int(put_raw_data.iloc[i]['OPT_LANCDRS']),
iq = put_raw_data.iloc[i]['OPT_TITULRS']/put_raw_data.iloc[i]['OPT_LANCDRS'],
timtoexp = put_raw_data.iloc[i]['CALC_TIME_TO_EXP'],
moneynes = put_raw_data.iloc[i]['CALC_MNYNS'],
impldvol = put_raw_data.iloc[i]['CALC_IV'] if put_raw_data.iloc[i]['CALC_IV'] > 0 else None,
polycofa = put_raw_data.iloc[i]['CALC_P_A'],
polycofb = put_raw_data.iloc[i]['CALC_P_B'],
polycofc = put_raw_data.iloc[i]['CALC_P_C'],
chosnvol = put_raw_data.iloc[i]['CALC_VOL'],
optdelta = put_raw_data.iloc[i]['CALC_DELTA'],
optgamma = put_raw_data.iloc[i]['CALC_GAMMA'],
optpctgm = put_raw_data.iloc[i]['CALC_PCT_GAMMA'],
opttheta = put_raw_data.iloc[i]['CALC_THETA'],
optbgt = put_raw_data.iloc[i]['CALC_BGT'] if put_raw_data.iloc[i]['CALC_BGT'] > 0 else None,
totdelta = int(put_raw_data.iloc[i]['TOT_DELTA']),
totgamma = int(put_raw_data.iloc[i]['TOT_GAMMA']),
ttpctgmm = int(put_raw_data.iloc[i]['TOT_PCT_GAMMA']),
tottheta = int(put_raw_data.iloc[i]['TOT_THETA']),
totbgt = int(put_raw_data.iloc[i]['TOT_BGT'])
)
options_array.append(this_option)
Is there a way to declare the ORM object or code the object instancing in a vectorized manner, avoiding the loops creating new instances?
I have tried Gord's suggestion and that indeed did the trick.
Start -- 2022-06-29 14:44:00.847775
End B3DB Init -- 0:00:02.259717
End CORE Read -- 0:00:00.485671
End Calculations -- 0:00:00.582443
End DADODB Init -- 0:00:00.056849
End ORM Instancing -- 0:00:03.634285
End DADODB Commit -- 0:00:00.963426
End DF.to_sql() Commit -- 0:00:00.206448
Total -- 0:00:08.188839
Starting with the data in a dataframe, putting it into ORM instances and writing would take roughly 4.5s. Just running the DF.to_SQL() method gets it done in 0.21s.

Python , how to get value from a loop and assign to another loop?

I have two loops below the first one is the timand and the second one is shared. What i want to know how can i assign each result to shared["score"] ? cause what i had try below i assign shared["score"] = timang["score"] just return 1 1 1 .... And also how can we return multiple response in python for example
return Response(shared_data, tomon_dat, status=status.HTTP_200_OK) is this possible?
#result of timang
Result: 0
Result: 1
Result: 0
Result: 0
Result: 1
Result: 1
for timang in tomon_dat:
tm_ins = QuestionaireAnswerModel.objects.get(id=timang["id"])
timang["score"] = tm_ins.score
timang["id"] = tm_ins.id
datatest = timang["score"]
for shared in shared_data:
questionaire_ins = QuestionaireModel.objects.get(random_code=shared["random_code"])
shared["title"] = questionaire_ins.title
shared["sub_title"] = questionaire_ins.sub_title
shared["idddd"] = questionaire_ins.id
answer_ins = SharedQuestionaire.objects.get(id=shared["id"])
shared["is_answered"] = (QuestionaireAnswerModel.objects.filter(shared_questionaire=answer_ins).count()) > 0
shared["score"] = timang["score"]

python list of dictionaries only updating 1 attribute and skipping others

I have a list of lists containing company objects:
companies_list = [companies1, companies2]
I have the following function:
def get_fund_amount_by_year(companies_list):
companies_length = len(companies_list)
for idx, companies in enumerate(companies_list):
companies1 = companies.values_list('id', flat=True)
funding_rounds = FundingRound.objects.filter(company_id__in=companies1).order_by('announced_on')
amount_per_year_list = []
for fr in funding_rounds:
fr_year = fr.announced_on.year
fr_amount = fr.raised_amount_usd
if not any(d['year'] == fr_year for d in amount_per_year_list):
year_amount = {}
year_amount['year'] = fr_year
for companies_idx in range(companies_length):
year_amount['amount'+str(companies_idx)] = 0
if companies_idx == idx:
year_amount['amount'+str(companies_idx)] = fr_amount
amount_per_year_list.append(year_amount)
else:
for year_amount in amount_per_year_list:
if year_amount['year'] == fr_year:
year_amount['amount'+str(idx)] += fr_amount
return amount_per_year_list
The problem is the resulting list of dictionaries has only one amount attribute updated.
As you can see "amount0" contains all "0" amounts:
[{'amount1': 12100000L, 'amount0': 0, 'year': 1999}, {'amount1':
8900000L, 'amount0': 0, 'year': 2000}]
What am I doing wrong?
I put list of dictionaries being built in the loop and so when it iterated it overwrote the last input. I changed it to look like:
def get_fund_amount_by_year(companies_list):
companies_length = len(companies_list)
**amount_per_year_list = []**
for idx, companies in enumerate(companies_list):
companies1 = companies.values_list('id', flat=True)
funding_rounds = FundingRound.objects.filter(company_id__in=companies1).order_by('announced_on')

python key dict error multilevel dict

I'm not entirely sure why im getting a dictionary key error. I'm trying to create a multi level dict with = sign and getting a key error on metrics, but not on the first two.
doc['timestamp']
and
doc['instance_id']
both work fine, but when it gets to metrics it gives me a metrics key error. I'm not entirely sure why.
doc = {}
doc['timestamp'] = datetime.now()
#doc['instance_id'] = get_cloud_app_name()
doc['instance_id'] = "MyMac"
cpu_dict_returned = get_cpu_info()
doc['metrics']['cpu_usage']['user_cpu'] = cpu_dict_returned['user_cpu']
doc['metrics']["cpu_usage"]['system_cpu'] = cpu_dict_returned['system_cpu']
doc['metrics']["cpu_usage"]['idle_cpu'] = cpu_dict_returned['idle_cpu']
doc['metrics']["cpu_usage"]['cpu_count'] = cpu_dict_returned['cpu_count']
You must create the sub-dictionnaries before using them:
doc = {}
doc['timestamp'] = datetime.now()
doc['instance_id'] = "MyMac"
cpu_dict_returned = get_cpu_info()
doc['metrics'] = {}
doc['metrics']['cpu_usage'] = {}
doc['metrics']['cpu_usage']['user_cpu'] = cpu_dict_returned['user_cpu']
doc['metrics']["cpu_usage"]['system_cpu'] = cpu_dict_returned['system_cpu']
doc['metrics']["cpu_usage"]['idle_cpu'] = cpu_dict_returned['idle_cpu']
doc['metrics']["cpu_usage"]['cpu_count'] = cpu_dict_returned['cpu_count']
You can do this more succinctly using a dictionary comprehension:
doc = {}
doc['timestamp'] = datetime.now()
doc['instance_id'] = "MyMac"
cpu_dict_returned = get_cpu_info()
doc['metrics'] = {
'cpu_usage':
{k: cpu_dict_returned.get(k)
for k in ['user_cpu', 'system_cpu', 'idle_cpu', 'cpu_count']}
}
Note that the sub dictionary cpu_usage is first created, and then the nested dictionary is inserted.

What Should Be In My Return?

I am using Python to parse an XML response from a SOAP web-service. The Customer returns about 40 values as you can see below. I would like to know if there is a way to make it so I only have to type one thing into my return statement and get all of the values returned? I tried to use for customer in doc.findall('.//Customer').itervalues() and that did not work as I believe that call is for dictionaries. Same results and reasoning behind .iteritems.
doc = ET.fromstring(response_xml)
for customer in doc.findall('.//Customer'):
customer_number = customer.findtext('CustomerNumber')
customer_first_name = customer.findtext('FirstName')
customer_last_name = customer.findtext('LastName')
customer_middle_name = customer.findtext('MiddleName')
customer_salutation = customer.findtext('Salutation')
customer_gender = customer.findtext('Gender')
customer_language = customer.findtext('Language')
customer_address1 = customer.findtext('Address1')
customer_address2 = customer.findtext('Address2')
customer_address3 = customer.findtext('Address3')
customer_city = customer.findtext('City')
customer_county = customer.findtext('County')
customer_state_code = customer.findtext('StateCode')
customer_zip_code = customer.findtext('ZipCode')
customer_phone_number = customer.findtext('PhoneNumber')
customer_business_phone = customer.findtext('BusinessPhone')
customer_business_ext = customer.findtext('BusinessExt')
customer_fax_number = customer.findtext('FaxNumber')
customer_birth_date = customer.findtext('BirthDate')
customer_drivers_license = customer.findtext('DriversLicense')
customer_contact = customer.findtext('Contact')
customer_preferred_contact = customer.findtext('PreferredContact')
customer_mail_code = customer.findtext('MailCode')
customer_tax_exempt_Number = customer.findtext('TaxExmptNumber')
customer_assigned_salesperson = customer.findtext('AssignedSalesperson')
customer_type = customer.findtext('CustomerType')
customer_preferred_phone = customer.findtext('PreferredPhone')
customer_cell_phone = customer.findtext('CellPhone')
customer_page_phone = customer.findtext('PagePhone')
customer_other_phone = customer.findtext('OtherPhone')
customer_other_phone_desc = customer.findtext('OtherPhoneDesc')
customer_email1 = customer.findtext('Email1')
customer_email2 = customer.findtext('Email2')
customer_optional_field = customer.findtext('OptionalField')
customer_allow_contact_postal = customer.findtext('AllowContactByPostal')
customer_allow_contact_phone = customer.findtext('AllowContactByPhone')
customer_allow_contact_email = customer.findtext('AllowContactByEmail')
customer_business_phone_ext = customer.findtext('BusinessPhoneExtension')
customer_internatinol_bus_phone = customer.findtext('InternationalBusinessPhone')
customer_international_cell = customer.findtext('InternationalCellPhone')
customer_external_x_reference_key = customer.findtext('ExternalCrossReferenceKey')
customer_international_fax = customer.findtext('InternationalFaxNumber')
customer_international_other_phone = customer.findtext('InternationalOtherPhone')
customer_international_home_phone = customer.findtext('InternationalHomePhone')
customer_preferred_name = customer.findtext('CustomerPreferredName')
customer_international_pager = customer.findtext('InternationalPagerPhone')
customer_preferred_lang = customer.findtext('PreferredLanguage')
customer_last_change_date = customer.findtext('LastChangeDate')
customer_vehicles = customer.findtext('Vehicles')
customer_ccid = customer.findtext('CCID')
customer_cccd = customer.findtext('CCCD')
webservice.close()
return
I would write that as a generator function yielding dicts where the key matches the findtext argument, e.g.:
fields = ['CustomerNumber', 'FirstName', 'LastName',
# ...
]
for customer in doc.findall('.//Customer'):
yield dict((f, customer.findtext(f)) for f in fields)
You either want to return a list of dicts:
customers = []
for customer in doc.findall('.//Customer'):
customer_dict = {}
customer_dict['number'] = customer.findtext('CustomerNumber')
customer_dict['first_name'] = customer.findtext('FirstName')
customer_dict['last_name'] = customer.findtext('LastName')
# ad nauseum
customers.append(customer_dict)
webservice.close()
return customers
Or you make a Customer class that handles this, and you return a list of customer instances.
I would use a dictionary of dictionaries:
doc = ET.fromstring(response_xml)
customers = {}
cust_dict = {}
for customer in doc.findall('.//Customer'):
cust_dict['customer_number'] = customer.findtext('CustomerNumber')
cust_dict['customer_first_name'] = customer.findtext('FirstName')
cust_dict['customer_last_name'] = customer.findtext('LastName')
snip snip...
customers[customer_number] = cust_dict # or whatever property you want to use to identify each customer, I'm assuming customer_number is some sort of id number
webservice.close()
return customers
That is if you don't have a class you can use to create a Customer object.

Categories

Resources