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

如何用Django Filter联合查询两张表并关联租户信息

如何查询关联租户信息的房产记录

嘿,我来帮你搞定这个查询需求!你要的是获取所有房产(Property)记录,同时带上关联协议(Agreement)里的租户姓名对吧?结合你给出的Django模型,这里有两种实用的实现方式:

方式一:获取每个房产的最新租户信息(无重复数据)

如果一个房产可能对应多个协议,你大概率不想返回重复的房产记录,这时候可以用Subquery来获取每个房产最新的协议租户信息:

from django.db.models import Subquery, OuterRef

# 子查询:获取当前房产的最新协议(按id倒序取第一条)
latest_agreement = Agreement.objects.filter(property=OuterRef('pk')).order_by('-id')

# 给每个房产标注租户姓名字段
properties = Property.objects.annotate(
    tenant_firstname=Subquery(latest_agreement.values('firstname')[:1]),
    tenant_lastname=Subquery(latest_agreement.values('lastname')[:1])
).all()

# 遍历结果示例
for prop in properties:
    tenant_name = f"{prop.tenant_firstname} {prop.tenant_lastname}" if prop.tenant_firstname else "无关联租户"
    print(f"房产名称: {prop.name}, 租户信息: {tenant_name}")

这种方式会保证每个房产只返回一条记录,没有关联协议的房产,租户字段会是None,可以轻松处理为空的情况。

方式二:获取房产的所有关联租户信息

如果你需要展示某个房产下的所有租户(不管多少个协议),可以用prefetch_related来批量预加载关联数据,避免N+1查询问题:

# 预加载所有关联的协议记录
properties = Property.objects.prefetch_related('prop').all()

# 遍历结果示例
for prop in properties:
    print(f"=== 房产名称: {prop.name} ===")
    if prop.prop.exists():
        for agreement in prop.prop.all():
            print(f"租户姓名: {agreement.firstname} {agreement.lastname}")
    else:
        print("暂无关联租户")

这里要注意你的模型里给Agreement的外键设置了related_name="prop",所以房产实例可以通过.prop直接访问所有关联的协议集合。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:30:42