Django: returning a selection of fields from a model based on their values?

Posted by AP257 on Stack Overflow See other posts from Stack Overflow or by AP257
Published on 2010-05-20T15:58:13Z Indexed on 2010/05/20 16:30 UTC
Read the original article Hit count: 209

Filed under:

I am working with some data over which I have little control. I'd like to return ONLY the fields of my model that aren't certain 'uninteresting' values (e.g. '0', 'X' or '-'), and access them individually in the template.

My model is like this:

class Manors(models.Model):
    structidx = models.IntegerField(primary_key=True, verbose_name="ID")    
    hills = models.CharField(max_length=100, null=True, blank=True, verbose_name="Number of fields") 

In my template, I return a QuerySet of Manors, and I'd like to output something like this if the hills field isn't uninteresting:

{% for manor in manors %}
{% if manor.hills %}<li>Hills blah blah: {{ manor.hills }}</li>{% endif %}
{% endfor %}

I want to avoid too much logic in the template. Ideally, the manor object would simply not return with the uninteresting fields attached, then I could just do {% if manor.hills %}.

I tried writing a model method that returns a dictionary of the interesting values, like this:

def get_field_dictionary(self):
    interesting_fields = {}
    for field in Manors._meta.fields:
        if field.value_to_string(self) != "N" and field.value_to_string(self) != "0" and field.value_to_string(self) != "-" and field.value_to_string(self) != "X":
            interesting_fields[field.name] = field.value_to_string(self)
    return interesting_fields

But I don't know how to access individual values of the dictionary in the template:

{% if manor.get_field_dictionary['hills'] %}<li>Hills blah blah: {{ manor.get_field_dictionary['hills'] }}</li>{% endif %}

gives a TemplateSyntaxError. Is there a better way to do this?

© Stack Overflow or respective owner

Related posts about django