On 12/19/06, k1000 <[EMAIL PROTECTED]> wrote:
Rails gives them together with query result. I know U don't like to
compare with it ;) but it would be nice feature.
Probably it's possible to iterate query object and take humanized names
from model definitions?
Any clues?
Assuming you're talking about something like this:
class Foo(models.Model):
title = models.CharField('this is the title', maxlength=100)
pub_date = models.DateTimeField()
and that you want to get the string 'this is the title', then what you
want is the verbose_name of the field. You can get that out of the
'fields' list on the '_meta' attribute of the model class (or of any
instance of it). Here are some approaches you might try:
f = Foo(title='blah')
f._meta.fields
[<django.db.models.fields.AutoField object at 0x1571b10>,
<django.db.models.fields.CharField object at 0x716470>]
f._meta.fields[1].verbose_name
'this is the title'
[field.verbose_name for field in f._meta.fields if field.name == 'title']
['this is the title']
[field.verbose_name for field in f._meta.fields if
field.verbose_name != field.name]
['ID', 'this is the title']
The first approach there relies on looking at the list of fields, and
picking one out specifically, which is the easiest option if you can
do it.
The second iterates over the list of fields looking for a field named
'title' and pulls out its verbose_name; if all you know in advance is
the name of the field you want the verbose_name for, this is easiest.
The third iterates over the list of fields looking for any fields
whose verbose_names don't match the actual names of the fields; this
will always get the automatic 'id' field if the model has one (and so
you can safely ignore that), but the rest of the list it returns will
be any fields which had human-readable names explicitly passed in. If
you know nothing in advance about the model, that's probably the best
way to do it.
Advanced usage might be something like this:
field_dict = {}
for field in f._meta.fields:
if field.name != 'id' and field.verbose_name != field.name:
field_dict[field.name] = field.verbose_name
That could be done as a one-line list comprehension, but it loses
readability. Either way, you'd end up with this:
field_dict
{'title': 'this is the title'}
In other words, field_dict will get populated so that its keys are
names of fields which have explicitly-set verbose_name attributes, and
its values are the verbose_name attributes of those fields.
--
"May the forces of evil become confused on the way to your house."
-- George Carlin
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Django
users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---