Jeffrey Chidi
Jeffrey Chidi

Reputation: 351

How to get related set in django(Many to many field)

I have an Employee model

class Employees(models.Model):
name = models.CharField(max_length=200, help_text="Enter the name of the employee")
location = models.ManyToManyField('Coverage')

def __str__(self):
    return self.name'

And a Location model

class Coverage(models.Model):
name = models.CharField(max_length=300, help_text="Enter employee location")
time_needed = models.IntegerField(help_text="Enter time needed to get to work. eg (40 = > 40 minutes)")

def __str__(self):
    return self.name

How do i access coverage - time_needed from my templates with ( employees = Employees.objects.all())

I have tried {{employees.location.time_needed}} but it doesn't work. Any good answer would be appreciated.

ps : this is just a snippet of a bigger model class

Upvotes: 0

Views: 63

Answers (2)

Umair Mohammad
Umair Mohammad

Reputation: 4635

I guess, you can do something like this :

employees = Employees.objects.all()
for employee in employees:
   for location in employee.location.all():
      print(location.time_needed)

if you want to access a particular Coverage, then you can do something like this :

Coverage.objects.filter(id__in=employee.location.all().values('id')).values('time_needed')
# This will return time_needed of all the Coverage whose id matched the location ids of employee

Upvotes: 1

Lemayzeur
Lemayzeur

Reputation: 8525

employees = Employees.objects.all() is a queryset, you can't access fields with it. But instead if you iterate through it, you will have access to each instance, then you will be able to have location for any instance. Since location is a ManyToManyField location = models.ManyToManyField('Location'). you will need to iterate through it as well.

{% for employee in employees %}
    {{ employee.location.all }} // Location queryset

    {% for location in employee.location.all %}
          {{ location.time_needed }}
    {% endfor %}
{% endfor %}

If you don't really need to iterate through these fields. You can use slice to select an instance

{{ employees.0 }} will select the first employee instance depending on your queryset ordering

{{ employee.0.location.all.0 }} select the first location instance depending on your queryset ordering

{{ employee.0.location.all.0.time_needed }} will give you access to the value.

Or much clearer:

{% with employees.0 as employee %}
     {% with location as employee.location.all.0 %}
         {{ location.time_needed }}
     {% endwith %}
{% endwith %}

Upvotes: 2

Related Questions