many-to-many items in a template: check if any are not empty or none
Asked Answered
C

2

15

Django beginner question. I have the following model:

class Leg(models.Model):
    startpoint = models.CharField(max_length=50, help_text="examples: 'Smith Elementary' or 'riders' houses'; less than 50 characters.")
    endpoint = models.CharField(max_length=50, help_text="examples: 'Smith Elementary' or 'riders' houses'; less than 50 characters.")
    riders = models.ManyToManyField(Rider, blank=True)
    drivers = models.ManyToManyField(Driver, blank=True)

I make an instance of the model available in a template as 'leg'. In the template, I want to see if, for that instance, there are ANY associated drivers. I've tried {% if leg.drivers %} but that always seems to evaluate to True, regardless of whether there are any drivers or not for the leg.

How do I check to see if there are actually any drivers? Sorry for the basic question but I can't seem to figure it out.

Crigger answered 26/8, 2012 at 13:56 Comment(3)
Try {% if leg.drivers_set.all() %}Krystynakshatriya
I think this would be for a backward relation like driver.leg_set.all. And you cant use braces in templates, at least not with the django template engine, jinja would accept that.Moye
Paranthesis are not used in templates, only in view. So would be: {% if leg.drivers_set.all %}Spleenful
M
18

{% if leg.drivers %} will always be true, because this will be a many to many manager. Try {% if leg.drivers.all %} to get all associated drivers.

Moye answered 26/8, 2012 at 14:4 Comment(1)
If driver objects are not used it will be much more efficient to do leg.drivers.count.Godfree
N
1

The for ... empty template tag is made for this. Simply loop leg.drivers.all and if you want to display some message if there are no drivers, then you can do so in the empty clause.

Nolan answered 26/8, 2012 at 14:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.