Question

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.

Was it helpful?

Solution

{% 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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top