django command to fetch all columns of a table
from django.apps import apps
def get_all_model_fields(app_label, model_name):
model = apps.get_model(app_label, model_name)
return model._meta.get_fields()
Explanation:
from django.apps import apps
: This line imports theapps
module from Django, which provides tools for working with applications and models in a Django project.def get_all_model_fields(app_label, model_name):
: This line defines a function namedget_all_model_fields
that takes two parameters:app_label
(the label of the Django app containing the model) andmodel_name
(the name of the model whose fields you want to fetch).model = apps.get_model(app_label, model_name)
: This line uses theget_model
function from theapps
module to retrieve the specified model based on the providedapp_label
andmodel_name
.return model._meta.get_fields()
: This line accesses the_meta
attribute of the model, which contains metadata about the model, including information about its fields. Theget_fields()
method retrieves all the fields (columns) of the model and returns them as a list.
This code, when provided with the appropriate app label and model name, will return a list of all the columns (fields) in the specified Django model.