Reputation: 1
What I want is to be able to sort baseball players by specific attributes via a drop down and display them as bootstrap cards in my template
Views.py
from django.shortcuts import render
from stats.models import *
def index(request):
player_list = Player.objects.all()
context_dict = {'player_list':player_list}
return render(request, 'stats/index.html', context=context_dict)
Models.py
from django.db import models
class Player(models.Model):
picture = models.ImageField(blank=True)
name = models.CharField(max_length=24)
number = models.IntegerField(unique=True)
jersey_name = models.CharField(max_length=20)
games_played = models.IntegerField()
at_bats = models.IntegerField(default=0)
average = models.DecimalField(max_digits=4, decimal_places=3)
hits = models.IntegerField()
doubles = models.IntegerField()
triples = models.IntegerField()
home_runs = models.IntegerField()
runs = models.IntegerField()
rbis = models.IntegerField()
def __str__(self):
return self.name
And here's what the I imagine the tag would look like in my template
{% for player in player_list.filter_by_some_attribute %}
HTML here
{% endfor %}
I looked for a solution here on SO and the Django docs but I'm fairly new to Django. I got the sense that custom template or filter tags might be what I'm looking for, but if I could get a push in the right direction that would be greatly appreciated.
Upvotes: 0
Views: 42
Reputation: 1254
Cool idea. So I think you would need to make filters for each attribute you want. To get the attribute from the dropdown you can use a form or ajax to send the attribute to your view. Then in your view you would run the filter for your database to return the objects. And then you can display the object in your template. Let's say you want players who have over 1000 games played. Your view could look like:
from django.shortcuts import render
def index(request):
if request.POST['games_played']==1000:
player_list = Player.objects.filter(games_played__gte=1000).order_by('name')
else:
player_list = Player.objects.all().order_by('name')
context_dict = {'player_list':player_list}
return render(request, 'stats/index.html', context=context_dict)
assuming you are sending data via a POST request. It seems like you would need many of those filters and if statements. You can even chain filters for more complex queries. Hope this helps.
Upvotes: 1