[Answer]-Accessing Foreign Key values from a foreign key referenced model in django

1πŸ‘

βœ…

The way you have designed there is no direct way to access it. As its one-to-many type of relation.

though you can loop on result.driver_set.all and that will give you access to driver object access and you can fetch user_id access.

{% for result in result_list %}
            <li>
            {% if result %}
                <a href="/rides/ridedetails/{{ result.pk }}">{{ result.type }}</a>
                <em>{{ result.ride_comment }}</em>
                {% for item in result.driver_set.all %}
                  {{item.user_id}}
                {% endfor %}
             {% endif %}
            </li>
        {% endfor %}
πŸ‘€Mutant

0πŸ‘

Driver is actually the through table of a many-to-many relationship between Ride and User. You should make that explicit, by declaring a ManyToManyField on Ride:

 users = models.ManyToManyField(User, through=Driver)

Now you can access that relationship more directly in the template:

{% for result in result_list %}
  ...
  {% for user in result.users.all %}
    {{ user.username }}
  {% endif %}

Although I’d repeat what other comments have said: your relationship seems backwards, in that surely a ride should only have a single driver.

Leave a comment