Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Django debugging: print model's containing data

Tags:

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.

like image 264
JackLeo Avatar asked May 31 '11 15:05

JackLeo


People also ask

What is __ str __ in Django?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.

How do I debug Python in Django?

If you want to debug Django using PTVS, you need to do the following: In Project settings - General tab, set "Startup File" to "manage.py", the entry point of the Django program. In Project settings - Debug tab, set "Script Arguments" to "runserver --noreload". The key point is the "--noreload" here.


1 Answers

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'] 
like image 198
zeekay Avatar answered Oct 04 '22 00:10

zeekay