能否将Django的Post与Topic模型合并展示并添加虚拟字段在模板循环时识别
问题解决方法
首先明确:你当前采用的多继承定义allon模型的方案不可行,Django的模型多表继承逻辑会将allon作为独立的第三张表存储数据,不会自动聚合Topic和Post两个模型的已有数据,无法实现你要的合并查询效果。
可用实现方案
直接通过合并查询集+动态添加属性的方式实现,无需额外定义新模型,步骤如下:
- 移除你定义的allon模型,原有Topic和Post模型保持不变
- 视图层合并两个模型的查询集,同时添加标识模型类型的虚拟属性
- 模板层直接通过虚拟属性判断数据所属模型类型
视图代码示例
from itertools import chain from .models import Topic, Post def home(request): # 分别获取两个模型的数据 topics = Topic.objects.all() posts = Post.objects.all() # 给所有数据添加虚拟字段标识类型 for topic in topics: topic.item_type = "topic" for post in posts: post.item_type = "post" # 合并数据集,如需按公共字段排序可使用sorted方法 all_items = list(chain(topics, posts)) # 排序示例:按id倒序排列 all_items = sorted(chain(topics, posts), key=lambda x: x.id, reverse=True) return render(request, 'forum/home.html', {'edd': all_items})
模板遍历示例
{% for item in edd %} <div> <h4>{{ item.title }}</h4> <p>{{ item.excerpt }}</p> <!-- 根据虚拟字段区分类型 --> {% if item.item_type == 'topic' %} <p>* 所属类型:话题</p> {% else %} <p>* 所属类型:帖子</p> {% endif %} </div> {% endfor %}
内容的提问来源于stack exchange,提问作者Kamarat AbdelSalam
相关产品推荐
相关产品推荐

