Search code examples
pythondjangomodelxlsxopenpyxl

How to get header and data from Models in Python?


Following this example (for openpyxl):

from openpyxl.workbook import Workbook

header = [u'Name', u'Email', u'Mobile', u'Current location',]
new_data = [[u'name1', u'email1@yahoo.com', 9929283421.0, u'xxxx'], [u'name2', u'email2@xyz.com', 9994191988.0, u'xxxx']]
wb = Workbook()

dest_filename = 'empty_book.xlsx'

ws1 = wb.active

ws1.title = "range names"

ws1.append(header)

for row in new_data:
    ws1.append(row)

wb.save(filename = dest_filename)

I have to split data that is going to be written into xlsx file on header and data itself.

So, how to extract header and data from Models in Django?


Solution

  • To modify the model's column name in database, do this:

    from django.db import models
    
    class MyModel(models.Model):
        gender = models.CharField(db_column=u'column_name', max_length=10)
    

    If you don't want to change the database's column name, use the verbose_name instead:

        gender = models.CharField(verbose_name=u'column_name', max_length=10)
    

    Then, when you are ready to output the excel sheet:

    for f in MyModel._meta.get_fields():
        print f.db_column  # or f.verbose_name
    

    This is how you iterate through all of the columns in your model and get their name.

    Why do you have to store the header name in a model? Why can't you store them statically in a list?

    When you have a header that spans multiple columns, there is just no way to store them in a model.