【问题标题】:How to get foreign key value instead of key in an ExtJS grid, using Django models?如何使用 Django 模型在 ExtJS 网格中获取外键值而不是键?
【发布时间】:2019-04-21 13:35:03
【问题描述】:

我正在使用 Django 1.11 和 ExtJS4 作为客户端创建一个简单的“任务管理器”Web 应用程序。

每个用户创建的条目都有自己的类别。 现在我有一个问题 - 在 ExtJS 网格中,条目的每个类别都显示为类别的“id”值。这是公平的,因为我使用外键来识别。

如何在 ExtJS 网格表中显示类型字段而不是 id?

我尝试使用 django 的“to_field = type”选项,它确实有效,而不是“category_id = id”,我得到了一个“category_id = type”。但是我的老师说这不是这种情况的解决方案,在后端我应该使用“id”进行操作。

models.py

class Entry(models.Model):
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateTimeField(auto_now_add=True)
    category = models.ForeignKey('Category', on_delete=models.CASCADE)


class Category(models.Model):
    type = models.CharField(max_length=255, unique=True)

在 views.py 中,我为 ExtJS 客户端发送 JSON 格式

views.py

def JS_entries_list(request):
    list_of_entries = Entry.objects.all().values()
    context = {
        'data': list(list_of_entries)
    }
    return JsonResponse(context)

这是我用于网格存储的 ExtJS 模型。在这里,您可以看到我将 'category_id' 作为 'int' 接收

Ext.define('Entry', {
        extend: 'Ext.data.Model',

        idProperty: 'entryID',

        fields: [{
            name: 'id',
            type: 'int',
        }, {
            name: 'uuid',
            type: 'string',
        }, {
            name: 'user_id',
            type: 'int',
        }, {
            name: 'headline',
            type: 'string',
        }, {
            name: 'body_text',
            type: 'string',
        }, {
            name: 'pub_date',
            type: 'date',
        }, {
            name: 'category_id',
            type: 'int',
        }, {
            name: 'fav_flag',
            type: 'bool',
        }, {
            name: 'published',
            type: 'bool',
        }]
    });

所以如果我做对了,现在我应该从数据库中收到一个“类别 ID”,然后在某个地方(在服务器或客户端)将其转换为“类别类型”并显示在 extjs 网格中。 现在,请您帮我找到一个正确而优雅的方法吗?

【问题讨论】:

    标签: python django extjs4


    【解决方案1】:

    在您的查询集上,您可以在.values() 中指定您想要从数据库中获取的值,然后您将获得一个对象列表。 例如list_of_entries = Entry.objects.all().values('headline', 'category__id', 'foo', 'bar')

    看看here

    【讨论】:

    • 谢谢你,Higor,这就是我要找的!我的坏我没有注意 .values() 在我的情况下,我只需要使用 .values('headline', 'category__type', 'foo', 'bar')
    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2017-07-25
    相关资源
    最近更新 更多