How to export querysets into Model Django? - python

How to export two querysets into one Model Django?
How can I write values from two querysets to the columns of the model table through a loop or in some other way?
--
for all rows in querysets:
queryset_1
last_row = queryset_1.last()
values_1 = last_row.name_1
values_2 = last_row.name_2
new_entry = Model_3(name_1=values_1, name_2=values_2)
new_entry.save()
queryset_2
last_row = queryset_2.last()
values_3 = last_row.name_3
values_4 = last_row.name_4
new_entry = Model_3(name_3=values_3, name_4=values_4)
new_entry.save()
--
queryset_1_min = queryset_1_filter.filter(pk__lte=limit)
queryset_2_min = queryset_2_filter.filter(pk__lte=limit)
queryset_3_min = queryset_3_filter.filter(pk__lte=limit)
for item in queryset_1_min:
values_1 = item.datetime
values_2 = item.temper_1
values_3 = item.temper_2
values_4 = item.g_rashod
values_5 = item.temper_nv
new_entry = Model_upload_summ(datetime=values_1, temper_1=values_2, temper_2=values_3, g_rashod=values_4, temper_nv=values_5)
# entry = Model_upload_summ(**item)
new_entry.save()
transaction.commit()
--
sqlite3.IntegrityError: NOT NULL constraint failed: application_model_upload_summ.temper_1_gvs
--
and add several data from queryset_2_min into Model_upload_summ
--
maybe ? =>
for item, item_2 in queryset_1_min, queryset_2_min:
values_1 = item.datetime
values_2 = item.temper_1
values_3 = item.temper_2
values_4 = item.g_rashod
values_5 = item.temper_nv
values_6 = item_2.temper_10

Related

Exact match with filter() Flask

I'am new to python and iam coding a small webapp to search in a database. Its fonctionnal but doesnt function well.
Example : If i search for a 'lieu', a 'Annee' and a 'Signataire' it doesnt give me the exact matches, instead it gives me every 'Signataire' even if its not the 'Annee' or the 'lieu' that i was looking for.
Update : I changed to elif, it helps finding the right "signataire" but still gives me others "signataire" that comes with 'lieu' and 'annee' iam a bit lost.
Here is the code :
'''
def search_results(search):
results = []
lieu = search.data['Lieu']
annee = search.data['Annee']
signataire = search.data['Signataire']
cote = search.data['Cote']
if search.data['Lieu'] or search.data['Annee'] or
search.data['Cote']:
qry = db_session.query(Cote).filter(and_(Cote.lieu.contains(lieu),Cote.annee.contains(annee),Cote.cote.contains(cote))
)
results = qry.all()
elif search.data['Signataire']:
qry = db_session.query(Cote).filter(or_(Cote.signataire_nom.contains(signataire),Cote.signataire_titre.contains(signataire)))
results = qry.all()
if not results:
flash('No results !')
return redirect('/')
else:
table = Results(results)
table.border = True
return render_template('results.html', table=table)
'''
This is because you are using "if" the second time and not "elif". So if there exists the Signataire, then your results are always all the signataire.
To resolve this you should use something like this:
def search_results(search):
results = []
lieu = search.data['Lieu']
annee = search.data['Annee']
signataire = search.data['Signataire']
cote = search.data['Cote']
if search.data['Lieu'] or search.data['Annee'] or search.data['Cote']:
qry = db_session.query(Cote).filter(and_(
Cote.lieu.contains(lieu),Cote.annee.contains(annee),Cote.cote.contains(cote))
)
results = qry.all()
elif search.data['Signataire']:
qry = db_session.query(Cote).filter(or_(
Cote.signataire_nom.contains(signataire),Cote.signataire_titre.contains(signataire)))
results = qry.all()
if not results:
flash('No results !')
return redirect('/')
else:
table = Results(results)
table.border = True
return render_template('results.html', table=table)
Please add the indent to all the other lines except the define function line**
I found a way to solve this. Thank you for your collaboration i appreciate.
Now i get the exact match.
I changed the code to this ->
def search_results(search):
lieu = search.data['Lieu']
annee = search.data['Annee']
signataire_nom = search.data['Signataire_nom']
signataire_titre = search.data['Signataire_titre']
cote = search.data['Cote']
sujet_1 = search.data['Sujet_1']
sujet_2 = search.data['Sujet_2']
sujet_3 = search.data['Sujet_3']
categorie = search.data['Categorie']
conditions = [
Cote.lieu.contains(lieu),
Cote.annee.contains(annee),
Cote.cote.contains(cote),
Cote.categorie.contains(categorie),
Cote.signataire_nom.contains(signataire_nom),
Cote.signataire_titre.contains(signataire_titre),
Cote.sujet_1.contains(sujet_1),
Cote.sujet_2.contains(sujet_2), Cote.sujet_3.contains(sujet_3)
]
results = []
if search.data['Lieu'] or search.data['Annee'] or search.data['Cote'] or search.data['Categorie'] or search.data['Signataire_nom'] or search.data['Signataire_titre'] or search.data['Sujet']:
qry = Cote.query.filter(and_( * conditions))
results = qry.all()
if not results:
flash('No results !')
return redirect('/')
else :
table = Results(results)
table.border = True
return render_template('results.html', table = table)
Jaybe

How do I insert into a Table one Primary Key and Two Foreign Keys?

I work with Rolls of plastic film in different legnth and width. And I'm creating a Database to store all the orders, and, in order to avoid repetition, I created separate tables for length(class(Comprimento)) and width(class(Largura)). I used UUID to create distinct ID's.
Now, I want to cross both tables in a Model class. Which is:
class Largura(Base):
__tablename__ = 'largura'
id = Column(GUID(), primary_key=True, default=lambda: str(uuid.uuid4()))
largura = Column(String)
modelos_l = relationship('Modelo', back_populates='larguras', cascade='all, delete')
def __repr__(self):
return f"<Largura {self.largura}>"
class Comprimento(Base):
__tablename__ = 'comprimento'
id = Column(GUID(), primary_key=True, default=lambda: str(uuid.uuid4()))
comprimento = Column(String)
modelos_c = relationship('Modelo', back_populates='comprimentos', cascade='all, delete')
def __repr__(self):
return f"<Comprimento {self.comprimento}>"
class Modelo(Base):
__tablename__ = 'modelo'
id = Column(GUID(), primary_key=True, default=lambda: str(uuid.uuid4()))
descricao = Column(String(50))
largura_id = Column(GUID(), ForeignKey("largura.id"), default=lambda: str(uuid.uuid4()))
comprimento_id = Column(GUID(), ForeignKey("comprimento.id"), default=lambda: str(uuid.uuid4()))
larguras = relationship('Largura', back_populates='modelos_l')
comprimentos = relationship('Comprimento', back_populates='modelos_c')
def __repr__(self):
return f"<Modelo {self.id}>"
Then, i created a file dedicated to my data insert on this table:
from DBModelPy3 import Comprimento,Largura,Modelo,session
from sqlalchemy import create_engine
import pandas as pd
#Pre Loading my CSV file
df = pd.read_csv("dataorged.csv", sep=',')
pd.set_option('display.float_format','{:.0f}'.format) #change the number format to hide the ','
cnx = create_engine('sqlite:///data_hub2.db', echo=True).connect()
df_modelo = df[['larg_ajustada', 'comp']] # My dataframe that contains the orders. I chose the specifics columns needed for this insertion.
#print(df_modelo)
# Loading the Tables from my database
df_largura = pd.read_sql_table('largura', cnx)
df_comprimento = pd.read_sql_table('comprimento', cnx)
With everything loaded I decided to combine all the legnths and widths i had already on my two tables (df_largura and df_comprimento), and then filtered using the original file which contains the orders.
# COMBINING ALL THE LENGTH AND WIDTH OF MY TABLES
model_num = []
for n_larg in range(len(df_largura)):
db_larg = str(df_largura['largura'][n_larg])
for n_comp in range(len(df_comprimento)):
db_comp = df_comprimento['comprimento'][n_comp]
combined = str(db_larg) + "x" + str(db_comp)
model_num.append([db_larg,db_comp,combined])
df_modelos_ex = pd.DataFrame(model_num)
df_modelos_ex.columns = ['larg','comp','combined']
With these, i had all possible combinations on my dataframe.
And created the combined variable to match later
modelos_existentes = []
# COMBINATIONS THAT APPEAR IN THE ORDER DATAFRAME #
for item in range(len(df_modelo)):
mod_larg = df_modelo['larg_ajustada'][item]
mod_comp = df_modelo['comp'][item]
mod_comb = str(mod_larg) + "x" + str(mod_comp)
modelos_existentes.append([mod_larg,mod_comp,mod_comb])
df_mod_existentes = pd.DataFrame(modelos_existentes)
df_mod_existentes.columns = ['ex_larg','ex_comp','ex_comb']
df_limpo = df_mod_existentes.drop_duplicates(subset=['ex_comb'])
df_limpo.reset_index(drop=True, inplace=True)
With all my elements, then the madness began.
I started a loop to run through all my Dataframes:
for l_row in range(len(df_limpo)): # For Each Row in my dataframe which contains the orders,
larg = df_limpo['ex_larg'][l_row] # create variable for width
comp = df_limpo['ex_comp'][l_row] # create variable for lenght
comb = df_limpo['ex_comb'][l_row] # create variable for combination of both
for n_row in range(len(df_largura)): # For each row in my width table from DB,
db_larg_id = df_largura['id'][n_row] # I create a Variable for the PK from width
db_larg_largura = df_largura['largura'][n_row] # Create a Variable with the value
lar = session.query(Largura).filter(Largura.id == db_larg_id).first()
if db_larg_largura == larg: # If the value on my table matches the value of the row in the order,
for m_row in range(len(df_comprimento)): # For each length in my table on the DB,
db_comp_id = df_comprimento['id'][m_row]
db_comp_comprimento = df_comprimento['comprimento'][m_row]
compr = session.query(Comprimento).filter(Comprimento.id == db_comp_id).first()
if db_comp_comprimento == comp: # If the value on my table matches the value of the row in the order
new_model = Modelo(descricao=df_limpo['ex_comb'][n_linha], larguras=lar, comprimentos=compr)
from here, i would only add the session.add(new_model) and session.commit() to finish my code.
But it's not adding.
What I would like is for my Modelo table be like:
MODELO Table
ID(PK) | DESCRIPTION (Combined values String) | Largura_id (width_id, FK) | Comprimento_id (length_id, FK)
Sorry about the long explanation. Tried my best!
If anyone have the same trouble:
##########################
# ADDING TO THE DATABANK #
##########################
lista_a = [] #Created an empty List
for n_linha in range(len(df_limpo)): #Ran through my dataframe
larg_a = df_limpo['ex_larg'][n_linha] #Extracted width and length from it
comp_a = df_limpo['ex_comp'][n_linha]
for m_linha in range(len(df_largura)): #Ran my width table from database
db_larg_id = df_largura['id'][m_linha]
db_larg_largura = df_largura['largura'][m_linha]
if larg_a == db_larg_largura: #Checked if the width from my dataframe matches the one on the table
lista_a.append([larg_a,comp_a,db_larg_id]) #appended to the list_a
#print(lista_a)
df_lista_a = pd.DataFrame(lista_a) #Created a new Dataframe
df_lista_a.columns = ['larg','comp','id_larg']
lista_b = [] #Created a new list
for n_row in range(len(df_lista_a)): #Ran through my new dataframe
larg_b = df_lista_a['larg'][n_row] #Extracted each column from it
comp_b = df_lista_a['comp'][n_row]
larg_b_id = df_lista_a['id_larg'][n_row]
#df_limpo_lrow = df_limpo['ex_larg'][n_row]
#df_limpo_crow = df_limpo['ex_comp'][n_row]
#df_limpo_cbrow = df_limpo['ex_comb'][n_row]
#print(larg_b,comp_b,larg_b_id,n_row)
for m_row in range(len(df_comprimento)): #Ran through my lenght table
db_comp_id = df_comprimento['id'][m_row]
db_comp_comprimento = df_comprimento['comprimento'][m_row]
if comp_b == db_comp_comprimento: #Check if the lenght from dataframe matches the lenght on my table on the database
#print(larg_b,comp_b,n_row,m_row,df_limpo_lrow)
lista_b.append([larg_b,comp_b,larg_b_id,db_comp_id]) #appended the lenght id to my list
break
#print(lista_b)
#print(len(df_lista_a),len(df_limpo),len(lista_b))
df_lista_b = pd.DataFrame(lista_b) #converted to Dataframe.
df_lista_b.columns = ['larg','comp','id_larg','id_comp']
# HERE's the ACTUAL INSERTION
for n_model in range(len(df_lista_b)): #For each model found on the list, extract the values and add to new_model.
mod_largura = df_lista_b['larg'][n_model]
mod_comprimento = df_lista_b['comp'][n_model]
mod_largura_id = df_lista_b['id_larg'][n_model]
mod_comprimento_id = df_lista_b['id_comp'][n_model]
lar = session.query(Largura).filter(Largura.id == df_largura['id'][1]).first()
compr = session.query(Comprimento).filter(Comprimento.id == df_comprimento['id'][1]).first()
new_model = Modelo(descricao=df_limpo['ex_comb'][n_model], larguras=lar, comprimentos=compr)
print("Modelo: " + df_limpo['ex_comb'][n_model] + " com Id's " + mod_largura_id + " e " + mod_comprimento_id + " adicionados!")
session.add(new_model)
session.commit()
Then it's done.

In Odoo 10,how can I specify a data in create_date,create_uid,instead of value in system,when I use method named 'create' to create a record

I create new record with the method named create() in local database with data pulled away from remote database.As we all know,there are four normal fields in Odoo such as create_date,write_date,create_uid,write_uid.I want these data to be in a remote databaseļ¼Œbut when I use method named create() to create the record,these data are the data at the time of local creation and not the remote data.
For example,in remote database,the creat_date is '2019-10-11',I can't change the value that is finally written to the local database even if I pass the value of the remote database into the dictionary.Finally,the value of field named create_date is '2019-12-03' rather than '2019-10-11'.The '2019-12-03' is the date now.The situation is similar for other fields such as write_date,create_uid,write_uid.
Please help me,thanks to everyone who thought about this question.
Following is my code.
The Class Model
class ReportRentalIncomeFromProperty(models.Model):
_name = 'report.rental.income.from.property'
_description = 'The report about the income from property rental'
_order = 'product_id, start_date'
# create_date = fields.Datetime('Created on')
create_uid = fields.Char('Created by')
# write_date = fields.Datetime('Last Modified on')
write_uid = fields.Char('Last Contributor')
product_id = fields.Many2one('product.product', 'Property House')
area_id = fields.Many2one('res.country.area', 'City')
district_id = fields.Many2one('res.country.district', 'District')
town_id = fields.Many2one('res.country.town', 'Town')
road_name = fields.Char('Road')
start_date = fields.Date('Start Date')
end_date = fields.Date('End Date')
should_pay = fields.Float('Should Pay')
real_pay = fields.Float('Real Pay')
balance_pay = fields.Float('Balance Pay')
rental_compliance_rate = fields.Float('Rental Compliance Rate(%)', group_operator="avg")
company_id = fields.Many2one('res.company', string='Company')
parent_company_id = fields.Many2one('res.company', related='company_id.parent_id', store=True,
string='Parent Company')
actual_business = fields.Many2many(
'rh.commercial.activities',
'house_rental_rent_income_business_db',
'actual_business_id',
'commercial_activities_id',
string='Actual business')
The function to pull away remote data to create new record in local database.
#api.multi
def synchronization_contract_performance_rate(self):
self.env['report.rental.income.from.property'].search([]).unlink()
product_dict = {}
A_product = self.env['product.product'].search([])
for a in A_product:
product_dict[a.name] = a.id
activities_dict = {}
D_activities = self.env['rh.commercial.activities'].search([])
for d in D_activities:
activities_dict[d.name] = d.id
address_dict = {}
i = 0
address_model_list = ['res.country.area', 'res.country.district', 'res.country.town']
address_field_list = ['area_id', 'district_id', 'town_id']
for addr in address_model_list:
C_address = self.env[addr].search([])
addr_dict = {}
for c in C_address:
addr_dict[c.name] = c.id
address_dict[i] = addr_dict
i += 1
record_list_1 = self.company_recursive_func()
for list_1 in record_list_1:
database = list_1[0]
link_url = list_1[1]
if link_url.startswith('http://'):
_uri = link_url.replace('http://', '')
my_odoo = odoorpc.ODOO(_uri, port=48080)
if link_url.startswith('https://'):
_uri = link_url.replace('https://', '')
my_odoo = odoorpc.ODOO(_uri, port=443, protocol='jsonrpc+ssl')
username = list_1[2]
password = list_1[3]
my_odoo.login(database, username, password)
company_id = list_1[4]
company_code = list_1[5]
product_actual_business_dict = {}
A_product_actual_business_ids = my_odoo.env['product.product'].search([])
A_product_actual_business = my_odoo.execute('product.product', 'read', A_product_actual_business_ids,
['actual_business'])
for a in A_product_actual_business:
name_list = []
for b in my_odoo.execute('rh.commercial.activities', 'read', a.get('actual_business'), ['name']):
name_list.append(b.get('name'))
product_actual_business_dict[a.get('id')] = name_list
remote_ids = my_odoo.env['report.rental.income.from.property'].search([])
remote_data_dict = my_odoo.execute('report.rental.income.from.property', 'read', remote_ids, ['product_id',
'start_date',
'create_date',
'create_uid',
'write_date',
'write_uid',
'end_date',
'should_pay',
'balance_pay',
'real_pay',
'rental_compliance_rate',
'area_id',
'road_name',
'district_id',
'town_id'])
for data in remote_data_dict:
remote_product_name = data.get('product_id')[1]
product_id = product_dict.get(remote_product_name + '(' + company_code + ')',
None)
if product_id:
i = 0
address_id_list = []
for address_field in address_field_list:
if data.get(address_field):
remote_address_name = data.get(address_field)[1]
local_address_id = address_dict[i].get(remote_address_name, None)
address_id_list.append(local_address_id)
else:
address_id_list.append(None)
i += 1
ids_list = []
find_names = product_actual_business_dict.get(data.get('product_id')[0])
for find_name in find_names:
id = activities_dict.get(find_name, None)
if id:
ids_list.append(id)
value = {
'product_id': product_id,
'area_id': address_id_list[0],
'district_id': address_id_list[1],
'town_id': address_id_list[2],
'road_name': data['road_name'],
'start_date': data['start_date'],
'end_date': data['end_date'],
'should_pay': data['should_pay'],
'real_pay': data['real_pay'],
'create_date': data['create_date'],
'create_uid': data['create_uid'][1],
'write_date': data['write_date'],
'write_uid': data['write_uid'][1],
'balance_pay':data['balance_pay'],
'rental_compliance_rate': data['rental_compliance_rate'],
'company_id': company_id,
'actual_business': [(6, 0, ids_list)]
}
self.env['report.rental.income.from.property'].create(value)
my_odoo.logout()
You can change standart odoo fields after you create your record with sql query
property_id = self.env['report.rental.income.from.property'].create(value)
self.env.cr.execute("UPDATE report_rental_income_from_property SET create_date='%s', create_uid=%s, write_date='%s', write_uid=%s WHERE id=%s" %
(value['create_date'], value['create_uid'], value['write_date'], value['write_uid'], property_id))

M2m relation breaks when passing filter parameters

I have a m2m relation between properties and images in my model like imageproperty = models.ManyToManyField(Property, blank = True). Im having an issue trying to filter properties with their associated images as whenever i pass a parameter in my query i get something like this and the images are not showing quiet good
. This is my code so far
def filter_properties(request, prop, p):
order = "creation_date"
if p["sort"]: order = p["sort"]
if p["asc_desc"] == "desc": order = '-' + order
results = Property.objects.filter(status = True)
for prop in results:
prop.images = prop.image_set.all()[:1] #Should i need to return in results so it brings values when filtering?
if p["name"] : results = results.filter(name__icontains=p["name"])
if p["price_from"] : results = results.filter(price__gte=int(p["price_from"]))
if p["price_to"] : results = results.filter(price__lte=int(p["price_to"]))
if p["category"]:
lst = p["category"]
or_query = Q(categories = lst[0])
for c in lst[1:]:
or_query = or_query | Q(categories = c)
results = results.filter(or_query).distinct()
return results
def search_properties_view(request):
try:
page = int(request.GET.get("page", '1'))
except ValueError:
page = 1
p = request.POST
prop = defaultdict(dict)
parameters = dict.fromkeys(
('name', 'price_from', 'price_to', 'currency_type', 'activity_type', 'sort', 'asc_desc'),
'',
)
parameters["category"] = []
for k, v in p.items():
if k == "category":
parameters[k] = [int(x) for x in p.getlist(k)]
elif k in parameters:
parameters[k] = v
elif k.startswith("name") or k.startswith("curency_type") or k.startswith("activity_type"):
k, pk = k.split('-')
prop[pk][k] = v
elif k.startswith("category"):
pk = k.split('-')[1]
prop[pk]["category"] = p.getlist(k)
if page != 1 and "parameters" in request.session:
parameters = request.session["parameters"]
else:
request.session["parameters"] = parameters
results = filter_properties(request, prop, parameters)
paginator = Paginator(results, 20)
try:
results = paginator.page(page)
except (InvalidPage, EmptyPage):
request = paginator.page(paginator.num_pages)
return render(request, 'propiedades/propiedades.html', {
'propiedades': request.POST,
'media_url': settings.MEDIA_URL,
'results': results,
'params': parameters,
'categories': PropertyCategory.objects.all()
})

writing to data to excel

I have data that I need to export to excel, I just don't know how to go about it, here's the view I'm using, I've commented out my attempts.A push to the right direction will be greatly appreciated.
def month_end(request):
"""
A simple view that will generate a month end report as a PDF response.
"""
current_date = datetime.now()
context = {}
context['month'] = current_date.month
context['year'] = current_date.year
context['company'] = 3
if request.method == 'POST':
context['form'] = MonthEndForm(user=request.user, data=request.POST)
if context['form'].is_valid():
#from reportlab.pdfgen import canvas
#import ho.pisa as pisa
context['month_no'] = int(context['form'].cleaned_data['month'])
context['company'] = context['form'].cleaned_data['company']
context['year'] = context['form'].cleaned_data['year']
context['month'] = datetime(context['year'], context['month_no'], 1).strftime('%B')
sql = '''SELECT "campaign_provider"."originator" as originator, "campaign_provider"."cost",
"campaign_receivedmessage"."network_id",
COUNT("campaign_provider"."originator") AS "originator_count",
"shortcode_network"."network"
FROM "campaign_receivedmessage"
LEFT OUTER JOIN "shortcode_network" ON ("shortcode_network"."id" = "campaign_receivedmessage"."network_id")
LEFT OUTER JOIN "campaign_provider" ON ("campaign_receivedmessage"."provider_id" = "campaign_provider"."id")
WHERE ("campaign_provider"."company_id" = %s
AND EXTRACT('month' FROM "campaign_receivedmessage"."date_received") = %s)
GROUP BY "campaign_provider"."originator", "campaign_provider"."cost", "campaign_receivedmessage"."network_id", "shortcode_network"."network"
ORDER BY "campaign_provider"."originator", "campaign_receivedmessage"."network_id" ASC
''' % (context['company'].id, context['month_no'])
context['rec_messages']= []
cursor = connection.cursor()
cursor.execute(sql)
data = cursor.fetchall()
for row in data:
dict = {}
desc = cursor.description
for (name, value) in zip(desc, row) :
dict[name[0]] = value
try:
dict['share'] = RevenueShare.objects.get(company=context['company'], priceband=dict['cost'], network=dict['network_id']).customer_share
dict['revenue'] = dict['originator_count'] * dict['share']
except:
dict['share'] = 0
dict['revenue'] = 0
context['rec_messages'].append(dict)
#context['rec_messages'] = ReceivedMessage.objects.filter(provider__company__id=context['company'].id, date_received__month=context['month_no'], date_received__year=context['year']).values('provider__originator', 'provider__cost', 'network').annotate(originator_count=Count('provider__originator')).order_by('provider__originator')
context['ret_messages'] = SentMessage.objects.filter(campaign__providers__company__id=context['company'].id, date_sent__month=context['month_no'], date_sent__year=context['year']).values('campaign__title').annotate(campaign_count=Count('campaign__title')).order_by('campaign__title')
context['revenue_share'] = RevenueShare.objects.filter(company=context['company'].id)
context['total_rec'] = 0
context['total_ret'] = 0
context['total_value'] = 0
context['total_cost'] = 0
context['queries'] = connection.queries
for message in context['rec_messages']:
context['total_rec'] += message['originator_count']
context['total_value'] += message['revenue']
for message in context['ret_messages']:
message['price'] = 0.175
message['cost'] = message['campaign_count'] * message['price']
context['total_ret'] += message['campaign_count']
context['total_cost'] += message['cost']
context['total'] = context['total_value'] - context['total_cost']
context['loaded_report'] = "yes"
data.append((context['data']))
data.append(('Orginator', 'cost', 'network_id', 'originator_count', 'network'))
file_name = '%s' % ('reports')
return generate_csv(file_name, data)
#template_data = render_to_string('reports/month_end_pdf.html', RequestContext(request, context))
#csv_data = StringIO.StringIO()
#csv_data.seek()
#simple_report = ExcelReport()34
#simple_report.addSheet("TestSimple")
#simple_report.writeReport(csv_data)
#response = HttpResponse(simple_report.writeReport(),mimetype='application/ms-excel')
#response['Content-Disposition'] = 'attachment; filename=simple_test.xls'
#return response
return render_to_response('reports/month_end.html', RequestContext(request, context))
#return render_to_response('reports/rfm_models.html', RequestContext(request, context))
#template_data = render_to_string('reports/month_end_pdf.html', RequestContext(request, context))
#pdf_data = StringIO.StringIO()
#pisa.CreatePDF(template_data, pdf_data, link_callback=fetch_resources)
#pdf_data.seek(0)
#response = HttpResponse(pdf_data, mimetype='application/pdf')
#response['Content-Disposition'] = 'attachment; filename=%s_%s_%s.pdf' % (context['company'].name.lower().replace(' ', '_'), context['month'].lower()[:3], context['year'])
if 'form' not in context.keys():
context['form'] = MonthEndForm(user=request.user, data=context)
return render_to_response('reports/month_end.html', RequestContext(request, context))
Have a look to xlwt http://pypi.python.org/pypi/xlwt
You could directly write CSV from MySQL records,
import csv
csv_writer = csv.writer(open(FILENAME,'w'), delimiter=',',quotechar="'")
data = cursor.fetchall()
for row in data:
csv_writer.writerow(row)
Full example at
http://snipplr.com/view/11970/simple-csv-dump-script/
SELECTQ="SELECT * FROM category"
FILENAME="dump.csv"
import MySQLdb
import csv
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="sakila")
dump_writer = csv.writer(open(FILENAME,'w'), delimiter=',',quotechar="'")
cursor = db.cursor()
cursor.execute(SELECTQ)
result = cursor.fetchall()
for record in result:
dump_writer.writerow(record)
db.close()

Categories