vendredi 24 juin 2016
Django - How to sort through a queryset based on the value of an attribute
I have created the following model which stores information for an html5 banner. I have a ForeignKey to associate the banner with a specific project.
class BannerCode(models.Model):
ROUNDS_LIST = (
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
('6', '6'),
)
project = models.ForeignKey(Project)
client = models.ForeignKey(Client, null=True, blank=True)
name = models.CharField(max_length=256, null=True, blank=True)
width = models.CharField(max_length=3, null=True, blank=True)
height = models.CharField(max_length=3, null=True, blank=True)
review_round = models.CharField(max_length=3, choices=ROUNDS_LIST, default=1)
I need to print out in my template something like this desired Output:
Round 1
banner name
banner name
banner name
banner name
Round 2
banner name
banner name
banner name
banner name
I am having trouble understanding how to loop through the objects and sort by the review_round attribute.
I created a custom filter and am able to sort them in one long list:
@register.filter
def sort_by(queryset, order):
return queryset.order_by(order)
In Template:
{% for b in project.bannercode_set.all|sort_by:'review_round' %}
{{ b.review_round }}
{% endfor %}
This loop works great for outputting something like this:
Current Output
banner name, round 1
banner name, round 1
banner name, round 2
banner name, round 3
How can I create a for loop that would match my desired output?
Inscription à :
Publier les commentaires (Atom)
Aucun commentaire:
Enregistrer un commentaire