I can't seem to figure out what is causing this: According to the following 2 modelsand the 'python manage.py shell' session shown after them, I am getting 2L as areturn value from a certain call when I would expect u'redhat 5.6' or similar.
> >>> from hostdb.models import Device, Interface
> >>> hostname = 'beijing.mitre.org'
> >>> dev = Interface.objects.get(fqdn=hostname).device
> >>> dev.status
> <Status: Online>
> >>> f = dev._meta.get_field('status')
> >>> f.value_from_object(dev)
> u'Online'
> >>> # Super -- this is exactly what I would expect. Now trouble
> >>> dev.distro
> <Distro: redhat 5.6>
> >>> print dev.distro
> redhat 5.6
> >>> f = dev._meta.get_field('distro')
> >>> f.value_from_object(dev)
> 2L
> >>> # what the hell?
Psychic debugging since you didn't post the Device model:
dev.distro is a foreign key to the Distro model. When you ask for the value via the get_field, you actually end up with the PK of the Distro rather than the distro instance.
Malcolm
unicode(myobject.myfield) // unicode(getattr(myobject, 'myfield'))
Am I being dense?
Tom
Okay, here's the problem.
>>> f = dev._meta.get_field('distro')>>> f.value_from_object(dev)2L
>>> f.attname'distro_id'>>>As others guessed, value_from_object() is returning the pk ID in thiscase.
Model "Distro" is the only model of mine showing this behavior, as it is theonly foreign key "target" model I have defined without named primary key.
But why do you need to get that value via the *field* object? The usual way to do it is simply to access the attribute directly on the model instance:unicode(dev.distro)or, if you have the field name as a string as you imply originally, use `getattr`:unicode(getattr(dev, 'distro'))