You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django模板多模型筛选:显示卡车司机对应注册车辆数问题

嘿,兄弟!刚接触Django就搞定多模型的使用已经很厉害了,要显示每个司机对应的注册卡车数量其实没那么复杂,给你几个实用的方案:

解决方案

1. 先确认你的模型关联(参考常见结构)

首先得保证你的Truck模型和Driver模型是通过外键关联的,比如这样:

# models.py
from django.db import models

class Driver(models.Model):
    name = models.CharField(max_length=100)
    # 可添加其他司机字段,比如联系方式、入职日期等

class Truck(models.Model):
    driver = models.ForeignKey(Driver, on_delete=models.CASCADE, related_name="trucks")
    license_plate = models.CharField(max_length=20)
    # 可添加其他卡车字段,比如车型、载重上限等

这里的related_name="trucks"是关键,它让我们能直接通过driver.trucks拿到这个司机名下的所有卡车。

2. 方法一:用annotate在视图层面统计(强烈推荐)

这种方法是在数据库层面一次性完成统计,效率超高,不会出现循环查库的性能问题。

在你的视图里,给Driver的查询集加上统计注解:

# views.py
from django.db.models import Count
from .models import Driver

def driver_list(request):
    # 用Count统计每个司机关联的trucks数量,结果存到truck_count字段中
    drivers = Driver.objects.annotate(truck_count=Count('trucks'))
    return render(request, 'driver_list.html', {'drivers': drivers})

然后在模板里直接调用这个统计好的字段,同时展示卡车信息:

<!-- driver_list.html -->
<h2>卡车司机列表</h2>
<table>
    <thead>
        <tr>
            <th>注册司机</th>
            <th>车辆数</th>
            <th>卡车信息</th>
        </tr>
    </thead>
    <tbody>
        {% for driver in drivers %}
        <tr>
            <td>司机#{{ driver.id }}</td>
            <td>{{ driver.truck_count }}</td>
            <td>
                {% for truck in driver.trucks.all %}
                    {{ truck.license_plate }} {% if not forloop.last %}|{% endif %}
                {% empty %}
                    无注册卡车
                {% endfor %}
            </td>
        </tr>
        {% endfor %}
    </tbody>
</table>

3. 方法二:在模型里加个统计方法(适合小数据量场景)

如果不想动视图代码,也可以在Driver模型里加一个方法来返回卡车数量,不过这种方法在数据多的时候会有性能问题(N+1查询),谨慎使用:

# models.py
class Driver(models.Model):
    name = models.CharField(max_length=100)
    
    def get_truck_count(self):
        # 每次调用都会单独查一次数据库,数据量大时会变慢
        return self.trucks.count()

然后模板里用{{ driver.get_truck_count }}就能显示数量,卡车列表的写法和上面一致。

4. 小提醒

  • 一定要确保Truck的外键关联正确,related_name别写错,不然没法通过driver.trucks拿到关联的卡车
  • 如果你的卡车有其他多对多关联导致统计重复,可以试试Count('trucks', distinct=True)来做去重统计

这样应该就能完美实现你想要的效果了,赶紧去试试吧!

内容的提问来源于stack exchange,提问作者Josh21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:53:43