How to get all field names of a table with Django ?

Published: September 10, 2022

Tags: Django; Database;

DMCA.com Protection Status

Examples of how to get all field names of a table with Django (SQLite):

Using Model meta API

To get all field names of a table with Django, a solution is to use Model _meta API:

table_name._meta.get_fields()

For example let's consider an application called notebook with a table named Article (models.py):

class Article(models.Model):
    notebook = models.ForeignKey(Notebook, null=True, blank=True, default = None,on_delete=models.CASCADE)
    url = models.CharField(max_length=1000, unique=True)
    title = models.CharField(max_length=1000)
    content = models.TextField()
    removed = models.BooleanField(default=False)

Get all field names in a view

from notebooks.models import Article

for e in Note._meta.get_fields():
    print(e)

returns

  (<django.db.models.fields.AutoField: id>,
  <django.db.models.fields.related.ForeignKey: notebook>,
  <django.db.models.fields.CharField: url>,
  <django.db.models.fields.CharField: title>,
  <django.db.models.fields.TextField: content>,
 <django.db.models.fields.BooleanField: removed>)

Get all field names using Django shell

Launch Django shell:

python manage.py shell

Then enter

from notebooks.models import Article

and

Article._meta.get_fields()

returns for example

  (<django.db.models.fields.AutoField: id>,
  <django.db.models.fields.related.ForeignKey: notebook>,
  <django.db.models.fields.CharField: url>,
  <django.db.models.fields.CharField: title>,
  <django.db.models.fields.TextField: content>,
 <django.db.models.fields.BooleanField: removed>)

References

Links Site
Get model's fields in Django stackoverflow
Model _meta API ocs.djangoproject.com
Writing your first Django app, part 2 docs.djangoproject.com