Django 外键关联数据

在设计数据库的时候,是得需要通过外键的形式将各个表进行连接。

原先的表是这样的

要想更改成这样:


下面是操作步骤:

有两张表是关联的

python 复制代码
# 在 models.py 里创建

class Department(models.Model):
    """
    部门表
    """
    title = models.CharField(verbose_name="标题", max_length=16)

class AssetSet(models.Model):
    """
    资产表
    """
    name = models.CharField(verbose_name="名称", max_length=32)
    price = models.IntegerField(verbose_name="价格")

    # 只适用于固定的选择
    category = models.SmallIntegerField(verbose_name="资产类型", choices=((1, '文具类'), (2, '3C类'), (3, '房产类')))

    # 外键 depart_id
    depart = models.ForeignKey(verbose_name="所属部门", to="Department", to_field="id", on_delete=models.CASCADE)

在 views.py 里定义函数

python 复制代码
# 在 views.py 里定义一个函数

def asset_list(request):
    queryset = models.AssetSet.objects.all().order_by("-id")

    return render(request, 'asset_list.html', { "queryset": queryset })

在对应的html文件里实现前端页面

html 复制代码
<table border="1px">
    <thead>
        <tr>
            <th>ID</th>
            <th>标题</th>
            <th>价格</th>
            <th>分类</th>
            <th>所属部门</th>
        </tr>
    </thead>
    <tbody>
        {% for obj in queryset %}
        <tr>
            <td>{{ obj.id }}</td>
            <td>{{ obj.name }}</td>
            <td>{{ obj.price }}</td>
            <td>{{ obj.get_category_display }}</td>
            <td>{{ obj.depart.title }}</td>   <!-- 直接调用对应的title就可以了 -->
        </tr>
        {% endfor %}
    </tbody>
</table>

点个赞呗~

相关推荐
郭小李10 分钟前
spring 中的 @EnableWebMvc注解和WebMvcConfigurer接口
java·后端·spring
马剑威(威哥爱编程)11 分钟前
Python 智能体开发实战 01:装了三遍环境还在报错?虚拟环境和 DeepSeek 一次配到位
开发语言·人工智能·python·agent
卷无止境17 分钟前
Skill 的安全边界在哪里:风险来源、验证思路与用户可用的防线
后端·python
TomEval20 分钟前
【测AI】第22篇:Agent 系统测试方法 — AI 学会“动手“了
人工智能·python·prompt·aigc·测试用例
速易达网络1 小时前
如何“训练”一个 .task 模型
python
星核0penstarry1 小时前
企业 API 向后兼容实战:版本控制、废弃字段通知与灰度发布策略
人工智能·后端·api·接口隔离原则·版本控制·架构设计·后端架构
PiaoKe___1 小时前
云手机技术解析:从 ARM 虚拟化到 Python 自动化实战
python·智能手机·自动化
学习论之费曼学习法1 小时前
无人值守AI内容矩阵实战(10):Windows 上让 Python 进程 7×24 活着
人工智能·windows·python·矩阵·powershell·进程守护
Norna1 小时前
锁文件里明明有哈希,PDM 为什么说没有?
python
大侠在此在在此1 小时前
我花了不到1块钱,用python把自己一年的1500次会话做成了个人知识库
python·llm