Pickels
Pickels

Reputation: 34660

Django's introspecting administrator: How does it work?

I don't really want to know Django I am actually more interested in the administrator. The thing that interests me is how they introspect the models to create the administrator back-end.

I browsed through the Django source code and found a little info but since it's such a big project I was wondering if there are smaller examples of how they do it?

This is just a personal project to get to understand Python better. I thought that learning about introspecting objects would be a good way to do this.

Upvotes: 0

Views: 98

Answers (3)

knutin
knutin

Reputation: 5133

If you really want to know how it works in order to learn Python, I would suggest looking at the source code. It is actually pretty well documented.

http://code.djangoproject.com/browser/django/trunk/django/contrib/admin

Upvotes: 0

Wolph
Wolph

Reputation: 80061

With Django it's a bit more than introspection actually. The models use a metaclass to register themselves, I will spare you the complexities of everything involved but the admin does not introspect the models as you browse through it.

Instead, the registering process creates a _meta object on the model with all the data needed for the admin and ORM. You can see the ModelBase metaclass in django/db/models/base.py, as you can see in the __new__ function it walks through all the fields to add them to the _meta object. The _meta object itself is generated dynamically using the Meta class definition on the model.

You can see the result with print SomeModel._meta or print SomeModel._meta.fields

Upvotes: 4

Ben Jackson
Ben Jackson

Reputation: 93860

This might get you started:

>>> class Foo:
...   x = 7
...
>>> f = Foo()
>>> dir(f)
['__doc__', '__module__', 'x']
>>> getattr(f, 'x')
7

Upvotes: 1

Related Questions