[Answer]-How to get header and data from Models in Python?

1👍

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.

👤Cheng

Leave a comment