问题
I'm trying to filter a list of objects in my database but I can't get it to work on the template using _set.all
. The strange thing is it's something I've done in two other places in my project but I cant see why it isnt working this time.
view.py:
class GolfMonthlyView(generic.ListView):
template_name="monthly_view/golf-monthly-view.html"
context_object_name='golf_monthly_view'
queryset = GolfMonthlyView.objects.all()
def get_context_data(self, **kwargs):
context = super(GolfMonthlyView, self).get_context_data(**kwargs)
context['golftour'] = golf_models.Tour.objects.all()
context['golftournament'] = golf_models.Tournament.objects.all()
models:
class Tour(models.Model):
name = models.CharField(max_length=100)
class Tournament(models.Model):
tour = models.ForeignKey('Tour', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
template html:
{% for info in golf_monthly_view %}
{% for competition in golftour %}
{% for golftournament in golftour.golftournament_set.all %}
<ul>
<li>{{golftournament.name}}</li>
</ul>
{% endfor %}
{% endfor %}
{% endfor %}
The good news out of all this is in trying to work out my problem its forced me to use the Django Shell for the first time properly. So I know the relationship is there and functional, it just isnt displaying in the template.
Edit: The working thing:
class RugbyMonthlyView(generic.ListView):
template_name="monthly_view/rugby-monthly-view.html"
context_object_name='rugby_monthly_view'
queryset = RugbyMonthlyView.objects.all()
def get_context_data(self, **kwargs):
context = super(RugbyMonthlyView, self).get_context_data(**kwargs)
context['competition'] = rugby_models.Competition.objects.all()
context['match'] = rugby_models.Match.objects.all()
return context
model.py:
class Competition(models.Model):
name = models.CharField(max_length=200)
class Match(models.Model):
competition = models.ForeignKey('Competition', on_delete=models.CASCADE)
html template:
{% for match_info in rugby_monthly_view %}
{% for competition in competition %}
*code*
{% for match in competition.match_set.all %}
*code*
{% endfor %}
{% endfor %}
{% endfor %}
回答1:
You have golftour.golftournament_set.all
nested in a loop on the context list golf_monthly_view
(not sure why you're doing this), which I think is empty because the ListView QuerySet is wrong:
queryset = GolfMonthlyView.objects.all()
# ^^^^ ?? This is not a model
If you yank off the outer for loop for example, the inner loops should proceed if the QuerySets are not empty:
{% for competition in golftour %}
{% for golftournament in golftour.tournament_set.all %}
<ul>
<li>{{golftournament.name}}</li>
</ul>
{% endfor %}
{% endfor %}
来源:https://stackoverflow.com/questions/47399586/django-set-all-filter-not-working-in-template