garak
garak

Reputation: 4813

Retrieving column name in Django Models

How do I retrieve names of the columns of a table in MySQL using Models in Django?

If I were using a MySQLdb API. I could have done it using the following:

cur = connection.cursor()
for k in cur.description:
    print k[0]

But I don't want to do it in the above manner.

I have the following defined in models.py

class Third(models.Model):
    studentname = models.CharField(max_length=90)
    rollnumber = models.CharField(max_length=30, primary_key=True)
    college = models.CharField(max_length=120)

My output should list "studentname", "rollnumber","college"

Upvotes: 4

Views: 4726

Answers (2)

m000
m000

Reputation: 6087

Something like this would also cover ForeignKey fields and manually-specified column names.

print(f'{"Field name":20} {"Column name"}')
print(50 * '-')
for f in Third._meta.fields:
    print(f'{f.name:20} {f.db_column or f.attname}')

Upvotes: 3

Geoffrey Wiseman
Geoffrey Wiseman

Reputation: 5637

Listing the fields of your 'Third' model class in python2:

for field in Third._meta.fields:
  print field.name

And python3:

print("Third fields:")
for field in Third._meta.fields:
    print( f"- {field.name}" )

Upvotes: 8

Related Questions