views:

72

answers:

2

Following my question at link text I'd like to separate the features in the template using categories such as Interior, Exterior, Mechanical etc.

I'm trying out the code below, but apparently it's not giving me what I want.

{% for feature in vehicle.features.all %}
    {% ifequal vehicle.features.type.type "Interior" %}
 <li>{{ feature }}</li>
    {% endifequal %}
{% endfor %}

How do I go about this?

A: 

Use Django's regroup tag: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup

Would probably end up looking something like:

{% regroup vehicle.features.all by type as vehicle_features %}

{% for feature in vehicle_features %}
  {% ifequal feature "Interior" %}
     <li>{{feature}}</li>
  {% endifequal %}
{% endfor %}
samuraisam
+1  A: 

You want:

{% for feature in vehicle.features.all %}
    {% ifequal feature.type.type "Interior" %}
        <li>{{ feature }}</li>
    {% endifequal %}
{% endfor %}

vehicle.features is a ManyToManyRelatedManager which can be used to access Feature objects, but does not actually carry Feature's relationships.

EDIT: In response to the comment below about doing this on the view, you could easily do:

interior_features = vehicle.features.filter(type__type='Interior')

and pass interior_features to the context of the template directly. This would actually make more sense as a method on the model:

def get_interior_features(self):
    return self.features.filter(type__type='Interior')

The result of this could be filtered further, of course, as needed.

options = vehicle.get_interior_features().filter(is_standard=False)

or something.

jcdyer
thanks jcd...it worked like a charm
BTW...just wondering is there a way to do this inside my view befor I render on to the template?
you're a life-saver...thank you. I'd up vote again if I could :)
how do I use the same method for displaying the feature_sets field? I tried the same ay, but for feature_sets and all I get is -'ManyRelatedManager' object has no attribute 'features' The features and feature_sets fields also appear in the CommonVehicle class, but they are skipped entirely in the template
It's not clear where your `feature_set` manager is coming from. How is `feature_set` different from `features`? At any rate, your error message tells you it is a `ManyRelatedManager`. So was `features`, so treat it the same.
jcdyer
@jcd I managed to sort out the issue...just a minor typo on my part :)