简体   繁体   中英

Accessing Foreign Key values from a foreign key referenced model in django

Models

class Ride(models.Model):  
    type = models.BooleanField(default=False)
    ride_comment = models.TextField(null=True,max_length=140,blank=True)
    def __unicode__(self):
        return self.ride_comment

class Driver(models.Model):
    ride_id = models.ForeignKey(Ride)
    user_id = models.ForeignKey(User)
    drv_carseats = models.SmallIntegerField(null=True,blank=False)
    def __unicode__(self):
        return self.user_id.username

Here is the Views.py

def search(request):
        result_list = Ride.objects.all()    
        return render_to_response('rides/search.html', {'result_list':result_list}, context )

My Template:

{% for result in result_list %}
            <li>
            {% if result %}
                <a href="/rides/ridedetails/{{ result.pk }}">{{ result.type }}</a>
                <em>{{ result.ride_comment }}</em>
             {% endif %}
            </li>
        {% endfor %}

I want do display the user details in the template, ie user_id and username from the Driver model of that associated ride_id. I have no idea how to get this!

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 %}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM