Michael Smith
Michael Smith

Reputation: 3447

Iterating 2 querysets in Django html?

I have two querysets. My first Queryset (services) has all of my service objects. My second Queryset (rating_values) has all of my rating values, where each index corresponds to the index in the services Queryset. For example services[1] corresponds with rating_values[1].

How do I loop through these two queries in an html page in django so so that I can display the service name along with the corresponding rating value?

To be clear, services contains service objects and rating_values contains decimal values. I pass the variables like this:

return render_to_response('services/display_services.html', {'user': request.user, 'services':services, 'rating_values': rating_values  })

I would like to do something like this:

{% for service in services %} 
    <p> {{service.service_name}} : {{ corresponding rating_value}} </p>  

Edit Here is my Service model:

class Service(models.Model):
    user_id= models.IntegerField(default=1)
    service_name = models.CharField(max_length=100)
    address = models.CharField(max_length=200)
    def __str__(self):              # __unicode__ on Python 2
        return self.service_name

Here is my Rating Model:

class Rating(models.Model):
    service_id= models.IntegerField(default=1)
    service_name= models.CharField(max_length=200)
    number_of_ratings = models.IntegerField()
    total_rating_value = models.IntegerField()
    rating_average = models.FloatField()
    def __str__(self):              # __unicode__ on Python 2
        return self.service_name

Upvotes: 1

Views: 1325

Answers (2)

Rajesh Chamarthi
Rajesh Chamarthi

Reputation: 18808

You can establish the relationship right in the model.

class Rating(models.Model):
    service= models.OneToOneField(Service, primary_key=True)
    service_name= models.CharField(max_length=200)
    number_of_ratings = models.IntegerField()
    total_rating_value = models.IntegerField()
    rating_average = models.FloatField()
    ....

You can then pass services and get the corresponding ratings..

{% for service in services %} 
    <p> {{service.service_name}} : {{ service.rating.rating_average }} </p> 

Upvotes: 3

H&#229;ken Lid
H&#229;ken Lid

Reputation: 23064

Just to answer the original question as well.

If you for some reason don't want a database relation between the models, you could convert the querysets to lists and zip them in the view, turning the querysets to a list of tuples.

view:

return render_to_response(
    'services/display_services.html',
    context_instance={
        'user': request.user,
        'services_and_ratings': zip(
            services.all(),
            rating_values.all()
        )
    }
)

template:

{% for service, rating in services_and_ratings %} 
    <p> {{ service.service_name }} : {{ rating.rating_average }} </p> 

Upvotes: 5

Related Questions