简体   繁体   English

从Django中的外键引用模型访问外键值

[英]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 这是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. 我想在模板中显示用户详细信息,即该关联ride_id的驱动程序模型中的user_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. 尽管您可以循环运行result.driver_set.all ,这将使您可以访问驱动程序对象访问权限,并且可以获取user_id访问权限。

{% 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. 驱动程序实际上是Ride和User之间的多对多关系的穿透表。 You should make that explicit, by declaring a ManyToManyField on Ride: 您应该通过在Ride上声明ManyToManyField来使之明确:

 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. 尽管我会重复其他评论所说的话:您的关系似乎倒退了,但肯定是一次乘车应该只有一个驾驶员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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