1
votes

So I want to create a method in my model class (I'm using a DetailView for the view) that returns a pre-approved set of field values and user friendly names that I can call in my template. This method has to check if the field values aren't the default field values for each approved field in the model and then return a list with the field value/name pairs to my template.

The problem is that I can't find a way of extracting field.value() and field.default as shown in my psuedocode below:

def displayFields(self):
    approvedFields = [  ('field1','Field One'),
                        ('field2','Field Two'),
                        ('field3','Field Three')
                        ]
    resultFieldPairs = []
    for fieldName in approvedFields:
        field = self._meta.get_field_by_name(fieldName[0])
        if field.value() != field.default:
            resultFieldPairs.append(tuple([fieldName[1], field.value()]))
    return resultFieldPairs

I can see from the errors I'm getting that self._meta.get_field_by_name() returns a RelatedObject, but the Django docs don't seem to be clear on this object's attributes and methods.

Please help.

1
What do expect to get from field.value() do you mean getattr(self, field.name)Stuart Leigh
Yeah, I just didn't know what the actual code was :Puser2667898

1 Answers

0
votes

I don't know how good it is to address the internal _meta attribute, normally it's not recommended, BUT - you can use

self._meta.get_field_by_name(fieldName[0])[0].default

notice the [0] because get_field_by_name returns a tuple in Django 1.6 with first element as the field object itself.

To get the value of this field for this instance, use: getattr(self, fieldName[0])

So the code would look like:

for fieldName in approvedFields:
        field = getattr(self, fieldName[0])
        if field != self._meta.get_field_by_name(fieldName[0]).default:
            resultFieldPairs.append(tuple([fieldName[1], field]))