#12096: Model fields are not accessible as attributes of the model class
-------------------------------------+-------------------------------------
Reporter: sejo | Owner:
Type: New feature | Status: new
Component: Database layer | Version: 1.1
(models, ORM) |
Severity: Normal | Resolution:
Keywords: model, docstrings, | Triage Stage: Accepted
attributes |
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by sephii):
To get this to work we need to change some low-level stuff since model
fields are stripped out by the metaclass to be put in Model._meta. Since
[http://www.sphinx-doc.org/en/stable/ext/autodoc.html Sphinx's autodoc
module allows to manually add members to a class] I think it would be
better to do in manually than trying to change the way Django models are
constructed.
Anyway, I came up with the following code that makes Sphinx's autodoc work
for Django models. It is '''very''' hackish and unsurprisingly makes some
tests fail, so I'm just putting this here for the record in case anyone
would want to take that over someday.
{{{
#!python
class ModelBase(type):
def __getattr__(self, attr):
if attr == '_meta':
raise AttributeError(attr)
try:
return self._meta.get_field(attr)
except FieldDoesNotExist:
raise AttributeError(attr)
@property
def __dict__(self):
try:
model_dict = {
f.name: f for f in self._meta.get_fields()
}
except AppRegistryNotReady:
model_dict = {}
model_dict.update(super(ModelBase, self).__dict__)
return model_dict
# Rest of ModelBase code...
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/12096#comment:10>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/062.97e27ed481f1f7f1b2f2d8747306bd0b%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.