Foros del Web » Programando para Internet » Python »

Escoger datos de las clases modelos

Estas en el tema de Escoger datos de las clases modelos en el foro de Python en Foros del Web. Saludos a todos, estoy desarrollando mi tesis en el lenguaje de programación Python y utilizando Django como framework, estoy cerca de terminar pero necesito ayuda ...
  #1 (permalink)  
Antiguo 04/06/2010, 14:33
 
Fecha de Ingreso: junio-2009
Mensajes: 10
Antigüedad: 14 años, 10 meses
Puntos: 0
Escoger datos de las clases modelos

Saludos a todos, estoy desarrollando mi tesis en el lenguaje de programación Python y utilizando Django como framework, estoy cerca de terminar pero necesito ayuda ya que no se como escoger diferentes atributos de las clases modelos, por ejemplo tengo la siguiente clase Tribunal, de la cual logro generar un Excel que me muestra todos los objetos de tipo de esa clase, o sea me muestra todos los presidentes que hay, todos los secretarios, todos los vocal y todos los asistentes, pero yo solo quiero que en el Excel salgan todos los presidentes y todos los secretarios, no quiero que salgan ni los vocal ni los asistentes, debajo de la clase Tribunal he puesto la función para generar el Excel.

Código Python:
Ver original
  1. class Tribunal(models.Model):
  2.     presidente=models.CharField(max_length=90)
  3.     secretario=models.CharField(max_length=90)
  4.     vocal=models.CharField(max_length=90)
  5.     asistente=models.CharField(max_length=90)
  6.     def __str__(self):
  7.                 return self.presidente    
  8.  
  9.  
  10. Esta es la función:
  11.  
  12. def excelejemplo(request):
  13.     book = xlwt.Workbook(encoding='utf8')
  14.     sheet = book.add_sheet('untitled')
  15.     default_style = xlwt.Style.default_style
  16.     datetime_style = xlwt.easyxf(num_format_str='dd/mm/yyyy hh:mm')
  17.     date_style = xlwt.easyxf(num_format_str='dd/mm/yyyy')
  18.     lista = Tribunal.objects.all() 
  19.     formato=ExcelFormatter()
  20.         estilosimple = ExcelStyle(vert=2,wrap=1)
  21.     formato.addBodyStyle(estilosimple)
  22.     formato.setWidth('presidente,secretario,vocal',3000)   
  23.     simple_report=ExcelReport()
  24.     simple_report.addSheet("Prueba sencilla")  
  25.     simple_report.addQuerySet(lista,REPORT_HORZ,formato)
  26.     response = HttpResponse(simple_report.writeReport(),mimetype='
  27. application/ms-excel')
  28.         response['Content-Disposition'] = 'attachment; filename=simple_test.xls'
  29.         return response

Espero que alguien me pueda ayudar, saludos a todos.

Última edición por AlvaroG; 04/06/2010 a las 15:07 Razón: coloreado de código
  #2 (permalink)  
Antiguo 04/06/2010, 15:19
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Escoger datos de las clases modelos

Hola,
- Podés re-crear la lista que pasás a addQuerySet eliminando los atributos que no necesites
- podés usar el método values() para limitar los campos obtenidos por la consulta.


Saludos.
  #3 (permalink)  
Antiguo 05/06/2010, 14:20
 
Fecha de Ingreso: junio-2009
Mensajes: 10
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Escoger datos de las clases modelos

Hice eso pero ahora me da el siguiente error: 'dict' object has no attribute '_meta'.
Saludos
  #4 (permalink)  
Antiguo 06/06/2010, 11:47
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Escoger datos de las clases modelos

Eso es porque values() no devuelve un QuerySet sino un diccionario.
Quizás quieras probar entonces crear el SQL a mano, fijate en el manual de Django para saber cómo


Saludos.
  #5 (permalink)  
Antiguo 06/06/2010, 19:00
 
Fecha de Ingreso: junio-2009
Mensajes: 10
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Escoger datos de las clases modelos

Amigo me lei la parte del manual de Django que habla sobre crear SQL a mano e hice una consulta, debajo pongo como me quedo el metodo, pero me lanza otro error ahora. No hay forma de hacerlo utilizando values()? e importar algún módulo que sea para diccionarios??. Personalmente me gustaba mas la idea de hacerlo utilizando values(), me he bajado el simplejson para ver si me puede ser util para trabajar con values() pero hasta ahora nada, espero que me pueda dar algun consejo para solucionar este problema de cualquier forma ya sea mediante una consulta SQL o utilizando values() saludos Alexander

Este es el error que se produce ahora:
AttributeError at /tesis/reporte/

'tuple' object has no attribute '_meta'

y así es como me quedó el método:

def excelejemplo(request):
lista = Tribunal.objects.all()
cursor=connection.cursor()
cursor.execute("SELECT presidente,secretario FROM tesis_tribunal")
row=cursor.fetchall()
simple_report=ExcelReport()
simple_report.addSheet("Prueba sencilla")
simple_report.addQuerySet(row,REPORT_HORZ)
response = HttpResponse(simple_report.writeReport(),mimetype= 'application/ms-excel')
response['Content-Disposition'] = 'attachment; filename=simple_test.xls'
return response
  #6 (permalink)  
Antiguo 06/06/2010, 19:22
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Escoger datos de las clases modelos

Creo que te equivocaste de manual Esa es la forma de hacer consultas con el módulo MySQL, no con lo que te ofrece Django. Fijate por acá: http://docs.djangoproject.com/en/dev/topics/db/sql/

Saludos.
  #7 (permalink)  
Antiguo 07/06/2010, 09:36
 
Fecha de Ingreso: junio-2009
Mensajes: 10
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Escoger datos de las clases modelos

Tienes razon amigo, me habia leido otro manual, mira, ahora modifique el metodo y me da este error: 'Manager' object has no attribute 'raw'. Estoy buscando a ver como lo soluciono, mientras le pongo el metodo a ver si me puede ayudar, saludos Alexander

Este es el metodo:

Código Python:
Ver original
  1. def excelejemplo(request):     
  2.     personas=Tribunal.objects.raw('SELECT presidente,secretario FROM tesis_tribunal')  
  3.     simple_report=ExcelReport()
  4.     simple_report.addSheet("Prueba sencilla")  
  5.     simple_report.addQuerySet(personas,REPORT_HORZ)
  6.     response = HttpResponse(simple_report.writeReport(),mimetype='application/ms-excel')
  7.         response['Content-Disposition'] = 'attachment; filename=simple_test.xls'
  8.         return response

Aqui debajo pongo la informacion completa del error por si sirve de ayuda


AttributeError at /tesis/reporte/

'Manager' object has no attribute 'raw'

Request Method: GET
Request URL: http://localhost/tesis/reporte/
Exception Type: AttributeError
Exception Value:

'Manager' object has no attribute 'raw'

Exception Location: e:\Tesis\sigaweb\tesis\views.py in excelejemplo, line 590
Python Executable: C:\Python26\python.exe
Python Version: 2.6.3
Python Path: ['e:\\Tesis\\sigaweb', 'C:\\Python26\\lib\\site-packages\\django_excel_templates-0.1-py2.6.egg', 'C:\\Python26\\lib\\site-packages\\simplejson-2.1.1-py2.6.egg', 'C:\\WINDOWS\\system32\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages', 'C:\\Python26\\lib\\site-packages\\PIL']
Server time: lun, 7 Jun 2010 11:02:33 +0200
Traceback Switch to copy-and-paste view

* C:\Python26\lib\site-packages\django\core\handlers\base.py in get_response
85. # Apply view middleware
86. for middleware_method in self._view_middleware:
87. response = middleware_method(request, callback, callback_args, callback_kwargs)
88. if response:
89. return response
90.
91. try:
92. response = callback(request, *callback_args, **callback_kwargs) ...
93. except Exception, e:
94. # If the view raised an exception, run it through exception
95. # middleware, and if the exception middleware returns a
96. # response, use that. Otherwise, reraise the exception.
97. for middleware_method in self._exception_middleware:
98. response = middleware_method(request, e)
▶ Local vars
Variable Value
callback
<function excelejemplo at 0x018F5D30>
callback_args
()
callback_kwargs
{}
e
AttributeError("'Manager' object has no attribute 'raw'",)
exc_info
(<type 'exceptions.AttributeError'>, AttributeError("'Manager' object has no attribute 'raw'",), <traceback object at 0x0154C878>)
exceptions
<module 'django.core.exceptions' from 'C:\Python26\lib\site-packages\django\core\exceptions.pyc'>
middleware_method
<bound method AuthenticationMiddleware.process_request of <django.contrib.auth.middleware.AuthenticationMidd leware object at 0x015B2BD0>>
receivers
[(<function _rollback_on_exception at 0x011EDD30>, None)]
request
<WSGIRequest GET:<QueryDict: {}>, POST:<QueryDict: {}>, COOKIES:{'sessionid': 'd9229436856e73d1501ae31aa7453503'}, META:{'ALLUSERSPROFILE': 'C:\\Documents and Settings\\All Users', 'APPDATA': 'C:\\Documents and Settings\\Alex\\Datos de programa', 'CLIENTNAME': 'APTO56102', 'COMMONPROGRAMFILES': 'C:\\Archivos de programa\\Archivos comunes', 'COMPUTERNAME': 'UCI-A9E57B275A5', 'COMSPEC': 'C:\\WINDOWS\\system32\\cmd.exe', 'CONTENT_LENGTH': '', 'CONTENT_TYPE': 'text/plain', 'DJANGO_SETTINGS_MODULE': 'sigaweb.settings', 'FP_NO_HOST_CHECK': 'NO', 'GATEWAY_INTERFACE': 'CGI/1.1', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Documents and Settings\\Alex', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate', 'HTTP_ACCEPT_LANGUAGE': 'es-es,es;q=0.8,en-us;q=0.5,en;q=0.3', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_COOKIE': 'sessionid=d9229436856e73d1501ae31aa7453503', 'HTTP_HOST': 'localhost', 'HTTP_KEEP_ALIVE': '300', 'HTTP_REFERER': 'http://localhost/tesis/Buscar_Tribunal/', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5', 'LOGONSERVER': '\\\\UCI-A9E57B275A5', 'NUMBER_OF_PROCESSORS': '2', 'OS': 'Windows_NT', 'PATH': 'C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\Sy stem32\\Wbem;C:\\Archivos de programa\\Intel\\DMIX;C:\\Archivos de programa\\Microsoft SQL Server\\90\\Tools\\binn\\;C:\\AppServ\\Apache2.2\\ bin;C:\\AppServ\\php6;C:\\AppServ\\MySQL\\bin;C:\\ Python26;C:\\Python26\\Lib\\site-packages;C:\\Python26\\Lib\\site-packages\\django\\bin;C:\\MiPrimeraWeb;C:\\Django; C:\\MiPrimeraWeb;C:\\Django\\django\\contrib\\auth ', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH' , 'PATH_INFO': u'/tesis/reporte/', 'PGLOCALEDIR': 'C:\\Archivos de programa\\PostgreSQL\\8.2\\share\\locale', 'PROCESSOR_ARCHITECTURE': 'x86', 'PROCESSOR_IDENTIFIER': 'x86 Family 15 Model 4 Stepping 3, GenuineIntel', 'PROCESSOR_LEVEL': '15', 'PROCESSOR_REVISION': '0403', 'PROGRAMFILES': 'C:\\Archivos de programa', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_HOST': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': u'', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.1 Python/2.6.3', 'SESSIONNAME': 'RDP-Tcp#1', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\WINDOWS', 'TEMP': 'C:\\DOCUME~1\\Alex\\CONFIG~1\\Temp', 'TMP': 'C:\\DOCUME~1\\Alex\\CONFIG~1\\Temp', 'USERDOMAIN': 'UCI-A9E57B275A5', 'USERNAME': 'Alex', 'USERPROFILE': 'C:\\Documents and Settings\\Alex', 'WINDIR': 'C:\\WINDOWS', 'WINGDB_ACTIVE': '1', 'WINGDB_PYTHON': 'C:\\Python26\\python.exe', 'WINGDB_SPAWNCOOKIE': 'z9BfwWWvolzIJrD3', 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x00AB40C0>, 'wsgi.file_wrapper': <class 'django.core.servers.basehttp.FileWrapper'>, 'wsgi.input': <socket._fileobject object at 0x01503EB0>, 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.version': (1, 0)}>
resolver
<RegexURLResolver sigaweb.urls (None:None) ^/>
response
None
self
<django.core.handlers.wsgi.WSGIHandler object at 0x01504D90>
settings
<django.conf.LazySettings object at 0x00E6E830>
urlconf
'sigaweb.urls'
urlresolvers
<module 'django.core.urlresolvers' from 'C:\Python26\lib\site-packages\django\core\urlresolvers.pyc'>
* e:\Tesis\sigaweb\tesis\views.py in excelejemplo
583. #date_style = xlwt.easyxf(num_format_str='dd/mm/yyyy')
584. #formato=ExcelFormatter()
585. #estilosimple = ExcelStyle(vert=2,wrap=1)
586. #formato.addBodyStyle(estilosimple)
587. #formato.setWidth('presidente,secretario,',3000)
588. def excelejemplo(request):
589. lista = Tribunal.objects.all()
590. personas=Tribunal.objects.raw('SELECT presidente,secretario FROM tesis_tribunal') ...
591. ##cursor=connection.cursor()
592. #cursor.execute("SELECT presidente,secretario FROM tesis_tribunal")
593. #row=cursor.fetchall()
594. simple_report=ExcelReport()
595. simple_report.addSheet("Prueba sencilla")
596. simple_report.addQuerySet(personas,REPORT_HORZ)
▶ Local vars

Última edición por AlvaroG; 07/06/2010 a las 10:36 Razón: arreglar coloreado de código
  #8 (permalink)  
Antiguo 07/06/2010, 10:40
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Escoger datos de las clases modelos

Parece que para Django 1.0 y 1.1 el método raw() no existe. Para esas versiones, el manual es éste: http://docs.djangoproject.com/en/1.1/topics/db/sql/, pero no veo que se devuelva un QuerySet, así que estamos de vuelta en el principio. Tendrías que manipular la lista para obtener solamente los datos que necesitas

Disculpa, tendría que haberte preguntado antes en qué versión estás


Saludos.
  #9 (permalink)  
Antiguo 07/06/2010, 11:33
 
Fecha de Ingreso: junio-2009
Mensajes: 10
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Escoger datos de las clases modelos

No amigo la culpa es mia que no habia dicho antes la version de Django con que trabajo, mira, yo ya habia probado manipulando la lista pero segun entiendo, que no se si estare equivocado porque no tengo mucha experiencia, a la hora de pasarsela al AddQuerySet() no la acepta ya que el AddQuerySet() solo acepta querysets y me lanza este error: 'list' object has no attribute '_meta'. Aqui debajo le pongo el metodo, si hubiera alguna forma de devolver un queryset con solo los parametros que me hacen falta(presidente, secretario) creo que se solucionaria todo pero no se como hacerlo.
Usted sabe alguna forma de manipular la lista para que me devuelva solo los paramertros que quiero? Saludos Alexander


def excelejemplo(request):
lista=Tribunal.objects.all()
datos=[]
for l in lista:
datos.append([l.presidente,l.secretario])
simple_report=ExcelReport()
simple_report.addSheet("Prueba sencilla")
simple_report.addQuerySet(datos,REPORT_HORZ)
response = HttpResponse(simple_report.writeReport(),mimetype= 'application/ms-excel')
response['Content-Disposition'] = 'attachment; filename=simple_test.xls'
return response
  #10 (permalink)  
Antiguo 07/06/2010, 12:09
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Escoger datos de las clases modelos

No sé cómo continuar sin saber antes algo que no te he preguntado: ¿de dónde sale la clase ExcelReport? ¿podrías pasar un enlace a la documentación? porque quizás haya algún método en la clase que acepte una lista o un diccionario en vez de un queryset :)


Saludos.
  #11 (permalink)  
Antiguo 07/06/2010, 13:52
 
Fecha de Ingreso: junio-2009
Mensajes: 10
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Escoger datos de las clases modelos

Si esa es una buena idea, voy a ir probando a ver que puedo averiguar, mientras le pongo aqui el codigo de la clase ExcelReport.

Código Python:
Ver original
  1. class ExcelReport(BaseReport):
  2.     """ MS Excel Style Reports """    
  3.     workbook = None
  4.     tempf = None
  5.     CHAR_WIDTH = 275
  6.    
  7.     def __init__(self):
  8.         self.workbook = xl.Workbook()
  9.         self.workbook._Workbook__use_cell_values = 0
  10.         self.cellformatters = {}
  11.         super(ExcelReport, self).__init__()
  12.      
  13.     def __del__(self):
  14.         if self.tempf and not self.tempf.closed:
  15.             self.tempf.close()
  16.    
  17.     def addCellFormatter(self,CellFormatter):
  18.         self.cellformatters[self.current_sheet] = CellFormatter
  19.        
  20.     def getCellFormatter(self):
  21.         return self.cellformatters
  22.    
  23.     def nextsheet(self,name=None):
  24.         """
  25.        Deprecated. Votovox is using this.
  26.        """
  27.         self.addSheet(name)
  28.    
  29.     def output(self):
  30.         """
  31.        Deprecated. Votovox is using this.
  32.        """
  33.         self.writeReport(self)
  34.    
  35.     def writeReport(self):
  36.         if not self.tempf:
  37.             self.tempf = StringIO.StringIO()
  38.            
  39.         for k, v in self.grids.iteritems():
  40.             self.current_x = 0
  41.             self.current_y = 0
  42.             ws = self.workbook.add_sheet(k)
  43.             grid = v.getGrid()
  44.             for col in grid:
  45.                 header_value = ''
  46.                 for item in col:
  47.                     if item.get_type() == ITEM_HEADER:
  48.                         header_value = item.get_value()
  49.                     if self.getFormatter()[k] != {}:
  50.                         if item.get_type() == ITEM_HEADER and self.getFormatter()[k].header_style is not None:
  51.                             self.style = self.getFormatter()[k].getHeaderStyle()
  52.                         elif self.getFormatter()[k].col_styles != {} and self.getFormatter()[k].getColumnStyle().has_key(header_value):
  53.                             self.style = self.getFormatter()[k].getColumnStyle(header_value)
  54.                         elif self.getFormatter()[k].alternate_color_style is not None and not helpers.isodd(self.current_x):
  55.                             self.style = self.getFormatter()[k].getAlternateColorStyle()
  56.                         elif self.getFormatter()[k].body_style is not None:
  57.                             self.style = self.getFormatter()[k].getBodyStyle()
  58.                         else:
  59.                             self.style = ExcelStyle().get_excel_style()
  60.                         if self.getFormatter()[k].getWidth() != {}:
  61.                             if self.getFormatter()[k].getWidth().has_key(header_value):
  62.                                 setwidth = self.getFormatter()[k].getWidth()[header_value]
  63.                                 self.__adjustwidth(item,setwidth)
  64.                             else:
  65.                                 self.__adjustwidth(item)
  66.                     else:
  67.                         self.__adjustwidth(item)
  68.                         self.style = ExcelStyle().get_excel_style()
  69.                     if self.get_format(item) != self.formatters['DEFAULT']:
  70.                         self.style.num_format_str = self.get_format(item)
  71.                     ws.write(
  72.                         self.current_x,
  73.                         self.current_y,
  74.                         item.get_value(),
  75.                         self.style
  76.                         )
  77.                     self.change_column_position()
  78.                 if self.getFormatter()[k] != {}:
  79.                     if self.getFormatter()[k].getFormula().has_key(header_value):
  80.                         excel_formula = '%s(%s%s:%s%s)' % (self.formatter.getFormula()[k][header_value],
  81.                                                            helpers.convert_to_letter(self.current_y),'2',
  82.                                                            helpers.convert_to_letter(self.current_y),
  83.                                                            self.current_x - 1)
  84.                         self.style = ExcelStyle().get_excel_style()
  85.                         ws.write(self.current_x,self.current_y,xl.Formula(excel_formula),self.style)
  86.                 self.change_row_position()
  87.         self.workbook.save(self.tempf)
  88.         return self.tempf.getvalue()
  89.  
  90.  
  91.     def __func_for_nums(item):
  92.         i = 0
  93.         style = '0.'
  94.         while i < item.get_percision():
  95.             style += '0'
  96.             i += 1
  97.         return style
  98.  
  99.  
  100.  
  101.     formatters = {
  102.         ITEM_DATETIME: 'M/D/YYYY h:mm:ss',
  103.         ITEM_DATE: 'M/D/YYYY',
  104.         ITEM_TIME: 'h:mm:ss',
  105.         ITEM_FLOAT: __func_for_nums,
  106.         ITEM_DECIMAL: __func_for_nums,
  107.         ITEM_INT: '0',
  108.         'DEFAULT': u'',
  109.     }
  110.    
  111.    
  112.     # Private internal methods
  113.     def __cellcord(self):
  114.         return self.current_x,self.current_y
  115.    
  116.     def __cursheet(self):
  117.         return self.workbook.get_sheet(self.sheetcount-2)
  118.    
  119.     def __adjustwidth(self,item,setwidth=0):
  120.         newlen =  item.get_length() * self.CHAR_WIDTH
  121.         if self.__cursheet().col(self.current_x).width < newlen:
  122.             if setwidth != 0:
  123.                 newlen = setwidth
  124.             self.__cursheet().col(self.current_y).width = newlen
  #12 (permalink)  
Antiguo 07/06/2010, 14:16
 
Fecha de Ingreso: junio-2009
Mensajes: 10
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Escoger datos de las clases modelos

Disculpame si formo desorden aqui pero es que no se a lo mejor la solucion esta aqui, esta clase que pongo tambien es para los reportes en Excel y es donde viene el metodo AddQuerySet(). No se si esta informacion es util, a lo mejor si.

Código Python:
Ver original
  1. class BaseReport(BaseDump):
  2.     """
  3.        Abstract BaseReport Class used by various reports
  4.        
  5.    """
  6.    
  7.     def __init__(self):
  8.         super(BaseReport, self).__init__()
  9.         self.grids = {}
  10.         self.current_sheet = None
  11.         self.current_x = self.current_y = 0
  12.         self.report_style = ReportStyle()
  13.         self.sheetcount = 0
  14.         self.formatter = {}
  15.    
  16.     def add_one_instance(self,inst,orientation,addheader=False):
  17.         """
  18.        Deprecated. Votovox is using this.
  19.        """
  20.         self.addQuerySet(inst,orientation,addheader)
  21.            
  22.     def addQuerySet(self,inst,orientation,addheader=False):
  23.         self.grids[self.current_sheet] = Grid()
  24.         self.current_x = self.current_y = 0
  25.         self.report_style.set_orientation(orientation)
  26.         headersadded = False
  27.         for i in inst:
  28.             if addheader and not headersadded:
  29.                 self.django_dump_obj(i,headers=True)
  30.                 headersadded = True
  31.             self.django_dump_obj(i)
  32.  
  33.     @accepts(object,object)
  34.     def addFormatter(self,formatter):
  35.         self.formatter[self.current_sheet] = formatter
  36.    
  37.     def getFormatter(self):
  38.         return self.formatter
  39.        
  40.  
  41.     formatters = {}
  42.  
  43.     def __get_format(self,key):
  44.         if self.formatters.has_key(key):
  45.             return self.formatters[key]
  46.         elif self.formatters.has_key("DEFAULT"):
  47.             return self.formatters["DEFAULT"]
  48.         return u''
  49.    
  50.     @accepts(object,Item)
  51.     def get_format(self,item):
  52.         format = self.__get_format(item.get_type())
  53.         if callable(format):
  54.             return format(item)
  55.         return format
  56.  
  57.     def addSheet(self,name=None):
  58.         self.sheetcount += 1
  59.         if name == None:
  60.             name = "Untitled Sheet #%s" % self.sheetcount
  61.         self.current_sheet = name
  62.         self.filters[self.current_sheet] = {}
  63.         self.formatter[self.current_sheet] = {}
  #13 (permalink)  
Antiguo 07/06/2010, 15:30
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Escoger datos de las clases modelos

La función que está "molestando" es django_dump_obj
La encontré definida por acá: http://django-excel-templates.google...xcelReports.py

Supongo que podrías crear una nueva clase, descendiente de ExcelReport, que reimplemente ese método o implemente otro similar.

Ahora mismo no tengo tiempo para proponerte una función, pero te sugiero concentrarte en esta parte:
Código Python:
Ver original
  1. for k, v in res.__dict__.iteritems():
  2.             if headers:
  3.                 self.grids[self.current_sheet].add(self.current_x,self.current_y,Item(k,v,res,header=True))
  4.                 self.change_column_position()
  5.                 continue
  6.             self.grids[self.current_sheet].add(self.current_x,self.current_y,Item(k,v,res))
  7.             self.change_column_position()
  8.         self.change_row_position()
ya que imprime los datos del diccionario que está dentro de cada elemento del QuerySet. Si lograras hacer que trabaje directamente con un diccionario (en vez de acceder al almacenado en el QuerySet) podrías usar values()


Saludos.
  #14 (permalink)  
Antiguo 08/06/2010, 13:19
 
Fecha de Ingreso: junio-2009
Mensajes: 10
Antigüedad: 14 años, 10 meses
Puntos: 0
Respuesta: Escoger datos de las clases modelos

Bueno mi amigo muchas gracias por la ayuda, pero aunque me duela decirlo creo que me voy a tener que rendir y hacerlo en pdf, ya que no tengo mucha experiencia con python y creo que quizas lograria hacer esa funcion pero el tiempo se me va acabando porque ya tengo la pre defensa en este mismo mes, de todas formas aprendi mucho con tus consejos, creo que voy a utilizar el reportlab para hacerlo en pdf, muchas gracias, Alexander
  #15 (permalink)  
Antiguo 08/06/2010, 13:50
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Escoger datos de las clases modelos

¡Éxitos!

Etiquetas: clases, modelos
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 07:27.