Python/Django debugging: print model's containing data
Solution 1
To check fields on a model I usually use ?
:
>>> Person?
Type: ModelBase
Base Class: <class 'django.db.models.base.ModelBase'>
String Form: <class 'foo.bar.models.Person'>
Namespace: Interactive
File: /home/zk/ve/django/foo/bar/models.py
Docstring:
Person(id, first_name, last_name)
You can also use help()
. If you have an instance of the model you can look at __dict__
:
>>> [x for x in Person().__dict__.keys() if not x.startswith('_')]
<<< ['first_name', 'last_name', 'id']
Solution 2
If you have the model instance(s) you can simply call:
model_queryset.all().values()
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values
For just the list of fields using the model class itself see Django: Get list of model fields?
or directly the documentation - for Django 1.10 there is a dedicated section on how to work with fields: https://docs.djangoproject.com/en/1.10/ref/models/meta/#retrieving-all-field-instances-of-a-model
Solution 3
I think you just want to use __dict__
on an instance of a model. (It won't give methods like tab completion in ipython though). Also using __doc__
is quite helpful usually.
Also look into inspect http://docs.python.org/library/inspect.html
Solution 4
Maybe try something suggested here:
data = serializers.serialize("json", models.MyModel.objects.all(), indent=4)
JSON format is easy to print and read ;)
Related videos on Youtube
JackLeo
Updated on July 09, 2022Comments
-
JackLeo almost 2 years
Maybe easy question but I don't know how to summarize it that I would find my answer.
Is it possible to print out all available fields of model?
For example in iPython I can import model and just write model name and tab will show all available fields the models have.
Is it possible to do this in code without using some sort of shell?
I would like to use some sort of command (e.a.
print_fields(self)
) and get what's inside the model.-
Bryce Siedschlaw almost 13 yearsAre you just wanted to know the field names or the data in the fields as well?
-
JackLeo almost 13 years@Bryce Siedschlaw: fields is enough :) thats for help, i got my answer
-
Risadinha about 7 years
-
-
JackLeo almost 13 yearsbecause i don't know what the fields are? Thats my main problem.
-
JackLeo almost 13 yearshelp() trowed all i needed :) so simple... damn i'm stupid :D oh,
?
works only in shell. -
zeekay almost 13 yearsOh good point, I misread and thought you were asking how to check in IPython!
-
Evhz about 7 yearseven a complete trace of a single object. awesome