首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何使用Django模型在ExtJS网格中获取外键值而不是键?

在Django中使用ExtJS网格获取外键值而不是键,可以通过以下步骤实现:

  1. 首先,在Django的模型中定义外键关系。假设有两个模型:ParentChildChild模型有一个外键字段指向Parent模型。
代码语言:txt
复制
from django.db import models

class Parent(models.Model):
    name = models.CharField(max_length=100)

class Child(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
  1. 在Django的视图中,使用select_related方法来预先加载外键关联的数据,以避免多次查询数据库。
代码语言:txt
复制
from django.http import JsonResponse
from myapp.models import Child

def get_children(request):
    children = Child.objects.select_related('parent').all()
    data = [{'id': child.id, 'name': child.name, 'parent': child.parent.name} for child in children]
    return JsonResponse(data, safe=False)
  1. 在ExtJS中,使用Ext.data.Store来加载数据,并在模型中定义字段映射。
代码语言:txt
复制
Ext.define('Child', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'id', type: 'int'},
        {name: 'name', type: 'string'},
        {name: 'parent', type: 'string', mapping: 'parent.name'}
    ]
});

var store = Ext.create('Ext.data.Store', {
    model: 'Child',
    proxy: {
        type: 'ajax',
        url: '/get_children/',
        reader: {
            type: 'json',
            rootProperty: ''
        }
    },
    autoLoad: true
});

var grid = Ext.create('Ext.grid.Panel', {
    store: store,
    columns: [
        {text: 'ID', dataIndex: 'id'},
        {text: 'Name', dataIndex: 'name'},
        {text: 'Parent', dataIndex: 'parent'}
    ],
    renderTo: Ext.getBody()
});

在上述代码中,mapping: 'parent.name'指定了parent字段的映射关系,将外键的名称作为字段的值。

这样,通过以上步骤,就可以在ExtJS网格中获取外键值而不是键。请注意,以上代码仅为示例,实际应用中需要根据具体情况进行调整。

腾讯云相关产品和产品介绍链接地址:

  • 腾讯云官网:https://cloud.tencent.com/
  • 云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 云数据库 MySQL 版:https://cloud.tencent.com/product/cdb-for-mysql
  • 云原生应用引擎(TKE):https://cloud.tencent.com/product/tke
  • 人工智能平台(AI Lab):https://cloud.tencent.com/product/ailab
  • 物联网开发平台(IoT Explorer):https://cloud.tencent.com/product/iothub
  • 移动推送服务(信鸽):https://cloud.tencent.com/product/tpns
  • 云存储(COS):https://cloud.tencent.com/product/cos
  • 区块链服务(TBC):https://cloud.tencent.com/product/tbc
  • 腾讯云元宇宙:https://cloud.tencent.com/solution/virtual-universe
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

16分8秒

人工智能新途-用路由器集群模仿神经元集群

领券