如何使用Django,MongoDB和数据透视表构建基于Web的仪表板

Hi, the freeCodeCamp community!

嗨,freeCodeCamp社区!

In this tutorial, I’d like to share with you an approach to data visualization in Python which you can further apply in the Django development.

在本教程中,我想与您分享一种使用Python进行数据可视化的方法,您可以将其进一步应用到Django开发中。

If you ever encountered the necessity to build an interactive dashboard or you’d like to try doing it, you’re welcome to walk through the steps from this tutorial.

如果您有必要构建交互式仪表板,或者想尝试这样做,欢迎您逐步学习本教程中的步骤。

If you have any questions regarding the process, please ask them in the comments. I'll be happy to assist you.

如果您对流程有任何疑问,请在评论中提问。 我很乐意为您提供帮助。

Here is the list of skills you’re going to master upon the tutorial completion:

这是教程完成后要掌握的技能列表:

  • How to create a basic Django app

    如何创建基本的Django应用

  • How to host remote MongoDB data in MongoDB Atlas

    如何在MongoDB Atlas中托管远程MongoDB数据

  • How to import JSON and CSV data to MongoDB

    如何将JSONCSV数据导入MongoDB

  • How to add a reporting tool to the Django app

    如何将报告工具添加到Django应用

Let’s start! 👩🏽‍💻👨🏽‍💻

开始吧! 👩🏽‍💻👨🏽‍💻

先决条件 (Prerequisites)

  • Basic knowledge of web development

    网站开发基础知识
  • Confident knowledge of Python

    Python有信心

  • Basic experience with NoSQL databases (e.g., MongoDB)

    具有NoSQL数据库(例如MongoDB)的基本经验

工具类 (Tools)

  • Django - a high-level Python web framework.

    Django-一个高级Python网络框架。

  • MongoDB Atlas - a cloud database service for modern applications. Here we’ll host our MongoDB database.

    MongoDB Atlas-用于现代应用程序的云数据库服务。 在这里,我们将托管我们的MongoDB数据库。

  • Flexmonster Pivot Table & Charts - a JavaScript web component for reporting. It will handle data visualization tasks on the client side.

    Flexmonster数据透视表和图表 -用于报告JavaScript Web组件。 它将在客户端处理数据可视化任务。

  • The MongoDB connector for Flexmonster - a server-side tool for fast communication between Pivot Table & MongoDB.

    适用于Flexmonster的MongoDB连接器 -一种服务器端工具,用于在数据透视表和MongoDB之间进行快速通信。

  • PyCharm Community Edition - an IDE for Python development.

    PyCharm社区版 -用于Python开发的IDE。

  • Kaggle data

    Kaggle数据

建立Django专案 (Establish a Django project)

If you’re new to Django development, that’s alright. In a step-by-step manner, we’ll set up everything to make our application outstanding.

如果您是Django开发的新手,那很好。 我们将逐步设置所有内容,以使我们的应用程序出色。

  • Make sure you've previously installed Django on your machine.

    确保您以前在计算机安装了Django

  • First, open the directory where you want your project to be created. Open the console and run the following command to create a new shiny Django project:

    首先,打开您要在其中创建项目的目录。 打开控制台并运行以下命令以创建一个新的闪亮的Django项目:

django-admin startproject django_reporting_project

django-admin startproject django_reporting_project

  • Next, navigate to this project:

    接下来,导航到该项目:

cd django_reporting_project

cd django_reporting_project

  • Let’s check if everything works as expected. Run the Django server:

    让我们检查一切是否按预期进行。 运行Django服务器:

python manage.py runserver

python manage.py runserver

Unless specified otherwise, the development server starts at port 8000. Open http://127.0.0.1:8000/ in your browser. If you can see this cool rocket, we are on the right track!

除非另有说明,否则开发服务器将从端口8000开始。 在浏览器中打开http://127.0.0.1:8000/ 。 如果您能看到这枚酷炫的火箭,那么我们走对了!

创建一个应用 (Create an app)

Now it’s time to create our application empowered with reporting features.

现在是时候创建具有报告功能的应用程序了。

If you don’t feel confident about the difference between projects and applications in Django, here’s a quick reference to help you figure it out.

如果您对Django中的项目和应用程序之间的区别不满意, 可以参考以下快速参考

  • Let’s call it dashboard:

    我们称之为dashboard

python manage.py startapp dashboard

python manage.py startapp dashboard

  • Next, open the project in your favorite IDE. I highly recommend using PyCharm since it makes the whole process of programming in Python a bliss. It also conveniently manages the creation of a project-specific isolated virtual environment.

    接下来,在您喜欢的IDE中打开项目。 我强烈建议使用PyCharm,因为它使Python编程的整个过程变得圆满。 它还方便地管理特定于项目的隔离虚拟环境的创建。

  • After an app is created, it’s necessary to register it at the project’s level. Open the django_reporting_project/settings.py file and append the app’s name to the end of the INSTALLED_APPS list:

    创建应用后,有必要在项目级别进行注册。 打开django_reporting_project/settings.py文件,并将应用程序的名称附加到INSTALLED_APPS列表的末尾:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'dashboard',
]

Hooray! Now the project knows about your app’s existence and we’re ready to move on to the database configuration.

万岁! 现在,该项目知道您的应用程序的存在,并且我们可以继续进行数据库配置了。

使用MongoDB Atlas设置MongoDB数据库 (Set up MongoDB database using MongoDB Atlas)

Let’s set the app aside until we’re done with arranging our database. I suggest we practice creating the remote MongoDB database by hosting it on MongoDB Atlas - a cloud database service for applications. Alternatively, you can prepare a local database and work with it in any convenient way (e.g., via MongoDB Compass or the mongo shell).

让我们将应用程序搁置一旁,直到完成数据库整理为止。 我建议我们通过将其托管在MongoDB Atlas(用于应用程序的云数据库服务)上来练习创建远程MongoDB数据库。 另外,您可以准备一个本地数据库并以任何方便的方式使用它(例如,通过MongoDB Compassmongo shell )。

  • After you've signed in your MongoDB account, create our first project. Let’s name it ECommerceData:

    登录MongoDB帐户后,创建我们的第一个项目。 让我们将其命名为ECommerceData

  • Next, add members (if needed) and set permissions. You can invite users to participate in your project via email address.

    接下来,添加成员(如果需要)并设置权限。 您可以通过电子邮件地址邀请用户参与您的项目。
  • Create a cluster:

    创建集群:
  • Choose the plan. Since we’re on our learning path, the simplest free plan will be sufficient for our needs.

    选择计划。 由于我们处在学习道路上,因此最简单的免费计划就足以满足我们的需求。
  • Select a cloud provider and region. The recommended regions are inferred via your location and marked with stars.

    选择云提供商和区域。 推荐的区域通过您的位置推断出来并标有星号。
  • Give a meaningful name to our brand-new cluster. Note that it can’t be changed later. Let’s name it ReportingData:

    给我们全新的集群起一个有意义的名字。 请注意,以后无法更改。 让我们将其命名为ReportingData

准备数据 (Prepare data)

While you’re waiting for your cluster to be created, let’s take a closer look at the data we’ll be working with. For this tutorial, we’re going to use the Kaggle dataset with transactions from a UK retailer. Using this data, we’ll try constructing a meaningful report which can serve for exploratory data analysis within a real organization.

在等待创建集群的过程中,让我们仔细看看将要使用的数据。 在本教程中,我们将使用Kaggle数据集处理来自英国零售商的交易。 使用这些数据,我们将尝试构建一个有意义的报告,该报告可用于实际组织中的探索性数据分析

Additionally, we’re going to use mock JSON data about marketing. It will help us to achieve the goal of establishing different reporting tools within the same application. You can choose any data of your preference.

此外,我们将使用有关营销的模拟JSON数据。 这将帮助我们实现在同一应用程序中建立不同报告工具的目标。 您可以选择自己喜欢的任何数据。

连接到您的集群 (Connect to your cluster)

Now that our cluster is ready, let’s connect to it!

现在我们的集群已经准备就绪,让我们连接它吧!

  • Whitelist your current IP address or add a different one.

    将您当前的IP地址列入白名单或添加其他IP地址。
  • Create a MongoDB user. The first one will have atlasAdmin permissions for the current project which means possessing the following roles and privilege actions. For security reasons, it’s recommended to auto-generate a strong password.

    创建一个MongoDB用户。 第一个将对当前项目具有atlasAdmin权限,这意味着具有以下角色和特权操作 。 出于安全原因,建议自动生成一个强密码。

  • Choose a connection method that suits you best. To test the connection, we can use the connection string for the mongo shell first. Later we’ll also use a connection string for an application.

    选择最适合您的连接方法 。 要测试连接,我们可以首先使用mongo shell的连接字符串。 稍后,我们还将为应用程序使用连接字符串。

  • Connect to it via the mongo shell. Open the command line and run the following:

    通过mongo shell连接到它。 打开命令行并运行以下命令:

mongo "mongodb+srv://reportingdata-n8b3j.mongodb.net/test"  --username yourUserName

mongo "mongodb+srv://reportingdata-n8b3j.mongodb.net/test" --username yourUserName

The interactive prompt will ask you for a password to authenticate.

交互式提示将要求您输入密码进行身份验证。

检查集群指标 (Check cluster metrics )

Phew! We’re almost there.

! 我们快到了。

Now get back to the page with the cluster summary and see how it came to life! From now, we can gain insights into write and read operations of the MongoDB database, the number of active connections, the logical size of our replica set - all this statistical information is at your hand. But most importantly now it’s possible to create and manage databases and collections.

现在回到包含集群摘要的页面,看看它是如何实现的! 从现在开始,我们将深入了解MongoDB数据库的写入和读取操作,活动连接数,副本集的逻辑大小-所有这些统计信息都在您手边。 但最重要的是,现在可以创建和管理数据库及集合。

建立资料库 (Create a database)

Create your first database and two collections. Let’s name them ecommerce, transactions, and marketing correspondingly.

创建您的第一个数据库和两个集合。 我们将它们分别命名为电子商务, 交易营销

Here’s how our workspace looks like now:

这是我们的工作区现在的样子:

Looks quite empty, doesn’t it?

看起来很空虚,不是吗?

将数据导入到MongoDB (Import data to MongoDB)

Let’s populate the collection with data. We’ll start with the retail data previously downloaded from Kaggle.

让我们用data填充集合 。 我们将从先前从Kaggle下载的零售数据开始。

  • Unzip the archive and navigate to the directory where its contents are stored.

    解压缩存档,然后导航到存储其内容的目录。
  • Next, open the command prompt there and import the data to the transactions collection of the ecommerce database using the mongoimport command and the given connection string for the mongo shell:

    接下来,在此处打开命令提示符,然后使用mongoimport命令和给定的mongo shell连接字符串将数据导入到电子商务数据库的交易记录集中:

mongoimport --uri "mongodb+srv://username:password@reportingdata-n8b3j.mongodb.net/ecommerce?retryWrites=true&w=majority" --collection transactions --drop --type csv --headerline --file data.csv

mongoimport --uri "mongodb+srv://username:password@reportingdata-n8b3j.mongodb.net/ecommerce?retryWrites=true&w=majority" --collection transactions --drop --type csv --headerline --file data.csv

❗Please remember to replace username and password keywords with your credentials.

❗请记住用您的凭据替换用户名密码关键字。



Congrats! We’ve just downloaded 541909 documents to our collection. What’s next?

恭喜! 我们刚刚下载了541909个文档到我们的收藏夹中下一步是什么?

  • Upload the dataset with marketing metrics to the marketing collection. Here’s the JSON file with the sample data we’re going to use.

    将具有营销指标的数据集上载到营销集合。 这是JSON文件,其中包含我们将要使用的示例数据。

Import the JSON array into the collection using the following command:

使用以下命令将JSON数组导入集合中:

mongoimport --uri "mongodb+srv://username:password@reportingdata-n8b3j.mongodb.net/ecommerce?retryWrites=true&w=majority" --collection marketing --drop --jsonArray marketing_data.json

mongoimport --uri "mongodb+srv://username:password@reportingdata-n8b3j.mongodb.net/ecommerce?retryWrites=true&w=majority" --collection marketing --drop --jsonArray marketing_data.json

If this data is not enough, we could dynamically generate more data using the mongoengine / PyMongo models. This is what our next tutorial of this series will be dedicated to. But for now, we’ll skip this part and work with the data we already have.

如果这些数据还不够,我们可以使用mongoengine / PyMongo模型动态生成更多数据。 这是我们本系列的下一篇教程将致力于的内容。 但是现在,我们将跳过这一部分,并使用已有的数据。



Now that our collections contain data, we can explore the number of documents in each collection as well as their structure. For more insights, I’d recommend using MongoDB Compass which is the official GUI tool for MongoDB. With it, you can explore the structure of each collection, check the distribution of field types, build aggregation pipelines, run queries, evaluate and optimize their performance. To start, download the application and use the connection string for Compass provided by MongoDB Atlas.

现在我们的集合包含数据,我们可以探索每个集合中的文档数量及其结构。 有关更多见解,我建议使用MongoDB指南针 ,它是MongoDB的官方GUI工具。 借助它,您可以探索每个集合的结构,检查字段类型的分布,建立聚合管道,运行查询,评估和优化其性能。 首先, 下载该应用程序,然后使用MongoDB Atlas提供的Compass连接字符串。

将网址格式映射到视图 (Map URL patterns to views)

Let’s get back to Django.

让我们回到Django。

  • Create urls.py in the app’s folder (inside dashboard). Here we’ll store URL routes for our application. These URL patterns will be matched with views defined in dashboard/views.py:

    在应用程序的文件夹(在dashboard )中创建urls.py 在这里,我们将存储应用程序的URL路由。 这些网址格式将与在dashboard/views.py定义的视图匹配

from django.urls import path
from . import views

urlpatterns = [
    path('report/retail', views.ecommerce_report_page, name='retail_report'),
    path('report/marketing', views.marketing_report_page, name='marketing_report'),
]
  • The application’s URLs need to be registered at the project’s level. Open django-reporting-project/urls.py and replace the contents with the following code:

    应用程序的URL需要在项目级别进行注册。 打开django-reporting-project/urls.py并将内容替换为以下代码:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('dashboard.urls')),
]

创建视图 (Create views)

A view is simply a function that accepts a web request and returns a web response. The response can be of any type. Using the render() function, we’ll be returning an HTML template and a context combined into a single HttpResponse object. Note that views in Django can also be class-based.

视图只是一个接受Web请求并返回Web响应的函数。 响应可以是任何类型。 使用render()函数,我们将返回一个HTML模板和一个上下文,并组合到一个HttpResponse对象中。 请注意,Django中的视图也可以基于类

  • In dashboard/views.py let’s create two simple views for our reports:

    让我们在dashboard/views.py为报告创建两个简单的视图:

from django.shortcuts import render


def ecommerce_report_page(request):
   return render(request, 'retail_report.html', {})


def marketing_report_page(request):
   return render(request, 'marketing_report.html', {})

创建模板 (Create templates)

  • Firstly, create the templates folder inside your app’s directory. This is where Django will be searching for your HTML pages.

    首先,在应用程序目录中创建templates文件夹。 Django将在此处搜索您HTML页面。

    Firstly, create the templates folder inside your app’s directory. This is where Django will be searching for your HTML pages.

    首先,在应用程序目录中创建templates文件夹。 Django将在此处搜索您HTML页面。

  • Next, let’s design the layout of our application. I suggest we add a navigation bar that will be displayed on every page. For this, we’ll create a basic template called base.html which all other pages will extend according to business logic. This way we'll take advantage of template inheritance - a powerful part of the Django’s template engine. Please find the HTML code on GitHub.

    接下来,让我们设计应用程序的布局。 我建议我们添加一个导航栏,该导航栏将显示在每个页面上。 为此,我们将创建一个名为base.html的基本模板,所有其他页面将根据业务逻辑进行扩展。 这样,我们将利用模板继承 -Django模板引擎的强大部分。 请在GitHub上找到HTML代码。

As you may have noticed, we’re going to use Bootstrap styles. This is to prettify our pages with ready-to-use UI components.

您可能已经注意到,我们将使用Bootstrap样式。 这是为了使用我们现成的UI组件来美化我们的页面。

Note that in the navigation bar, we’ve added two links that redirect to the report pages. You can do it by setting the link's href property to the name of the URL pattern, specified by the name keyword in the URL pattern. For example, in the following way:

请注意,在导航栏中,我们添加了两个重定向到报告页面的链接。 您可以通过将链接的href属性设置为URL模式的名称(由URL模式中的name关键字指定)来实现。 例如,通过以下方式:

href="{% url 'marketing_report' %}"

href="{% url 'marketing_report' %}"

  • It's time to create pages where the reports will be located. Let me show you how to create a retail report first. By following these principles, you can create as many other reporting pages as you need.

    现在是时候创建要在其中放置报告的页面了。 让我向您展示如何首先创建零售报告。 通过遵循这些原则,您可以根据需要创建任意数量的其他报告页面。
  1. In templates, create marketing_report.html.

    在模板中,创建marketing_report.html

  2. Add an extends tag to inherit from the basic template: {% extends "base.html" %}

    添加延伸标签以从基本模板继承: {% extends "base.html" %}

  3. Add a block tag to define our child template's content: {% block content %}{% endblock %}

    添加一个block标签来定义我们子模板的内容 {% block content %}{% endblock %}

  4. Within the block, add Flexmonster scripts and containers where the reporting components will be placed (i.e., the pivot table and pivot charts): <script src="https://cdn.flexmonster.com/flexmonster.js"></script> <div id="pivot"></div><div id="pivot_chart"></div>

    在该块内,添加将放置报表组件的Flexmonster脚本和容器(即数据透视表和数据透视图): <script src="https://cdn.flexmonster.com/flexmonster.js"></script> <div id="pivot"></div><div id="pivot_chart"></div>

  5. Add <script> tags where JavaScript code will be executed. Within these tags, instantiate two Flexmonster objects using init API calls.

    添加<script>标记,将在其中执行JavaScript代码。 在这些标签中,使用init API调用实例化两个Flexmonster对象。

var pivot = new Flexmonster({
    container: "#pivot",
    componentFolder: "https://cdn.flexmonster.com/",
    height: 600,
    toolbar: true,
    report: {}
});
var pivot_charts = new Flexmonster({
    container: "#pivot_charts",
    componentFolder: "https://cdn.flexmonster.com/",
    height: 600,
    toolbar: true,
    report: {}
});

You can place as many Flexmonster components as you want. Later, we’ll fill these components with data and compose custom reports.

您可以根据需要放置任意数量的Flexmonster组件。 稍后,我们将用数据填充这些组件并编写自定义报告。

设置MongoDB连接器 (Set up the MongoDB connector)

To establish efficient communication between Flexmonster Pivot Table and the MongoDB database, we can use the MongoDB Connector provided by Flexmonster. This is a server-side tool that does all the hard work for us, namely:

为了在Flexmonster数据透视表和MongoDB数据库之间建立有效的通信,我们可以使用Flexmonster提供的MongoDB连接器 。 这是一个服务器端工具,可以为我们完成所有艰苦的工作,即:

  1. connects to the MongoDB database

    连接到MongoDB数据库
  2. gets the collection’s structure

    获取集合的结构
  3. queries data every time the report’s structure is changed

    每次更改报表结构时查询数据
  4. sends aggregated data back to show it in the pivot table.

    发回汇总数据以在数据透视表中显示。

To run it, let’s clone this sample from GitHub, navigate to its directory, and install the npm packages by running npm install.

要运行它,让我们从GitHub克隆此示例 ,导航到其目录,然后通过运行npm install来安装 npm软件包。

  • In src/server.ts you can check which port the connector will be running on. You can change the default one. Here, you can also specify which module will handle requests coming to the endpoint ( mongo.ts in our case).

    src/server.ts您可以检查连接器将在哪个端口上运行。 您可以更改默认值。 在这里,您还可以指定哪个模块将处理到达端点的请求(在本例中为mongo.ts )。

  • After, specify the database credentials in src/controller/mongo.ts. Right there, add the connector string for application provided by MongoDB Atlas and specify the database’s name.

    之后,在src/controller/mongo.ts指定数据库凭据。 在此处,添加MongoDB Atlas提供的应用程序的连接器字符串,并指定数据库的名称。

定义报告 (Define reports)

Now we’re ready to define the report’s configuration on the client side.

现在,我们准备在客户端定义报告的配置。

  • Here’s a minimal configuration which makes the pivot table work with the MongoDB data via the connector:

    这是一个最小配置,它使数据透视表通过连接器与MongoDB数据一起工作:
var pivot = new Flexmonster({
    container: "#pivot",
    componentFolder: "https://cdn.flexmonster.com/",
    height: 600,
    toolbar: true,
    report: {
        "dataSource": {
            "type": "api",
            "url": "http://localhost:9204/mongo", // the url where our connector is running
            "index": "marketing" // specify the collection’s name
        },
        "slice": {}
    }
});
  • Specify a slice - the set of hierarchies that will be shown on the grid or on the chart. Here’s the sample configuration for the pivot grid.

    指定一个切片 -将在网格或图表上显示的一组层次结构。 这是枢轴网格的示例配置。

    Specify a slice - the set of hierarchies that will be shown on the grid or on the chart. Here’s the sample configuration for the pivot grid.

    指定一个切片 -将在网格或图表上显示的一组层次结构。 这是枢轴网格的示例配置。

"slice": {
        "rows": [
            {
                "uniqueName": "Country"
            }
        ],
        "columns": [
            {
                "uniqueName": "[Measures]"
            }
        ],
        "measures": [
            {
                "uniqueName": "Leads",
                "aggregation": "sum"
            },
            {
                "uniqueName": "Opportunities",
                "aggregation": "sum"
            }
        ]
    }

运行您的报告应用 (Run your reporting app)

Now that we’ve configured the client side, let’s navigate to the MongoDB connector’s directory and run the server:

现在,我们已经配置了客户端,让我们导航到MongoDB连接器的目录并运行服务器:

npm run build

npm run build

npm run start

npm run start

  • Next, return to the PyCharm project and run the Django server:

    接下来,返回PyCharm项目并运行Django服务器:

    Next, return to the PyCharm project and run the Django server:python manage.py runserver

    接下来,返回PyCharm项目并运行Django服务器: python manage.py runserver

  • Open http://127.0.0.1:8000/report/marketing. To switch to another report, click the report’s name on the navigation bar.

    打开http://127.0.0.1:8000/report/marketing 。 要切换到另一个报告,请在导航栏上单击该报告的名称。

It’s time to evaluate the results! Here you can see the report for the marketing department:

现在该评估结果了! 在这里,您可以查看营销部门的报告:

Try experimenting with the layout:

尝试试验布局:

  • Slice & dice the data to get your unique perspective.

    对数据进行切片切块以获得独特的视角。

  • Change summary functions, filter & sort the records.

    更改摘要功能,对记录进行过滤排序

  • Switch between classic and compact form to know what feels better.

    经典紧凑形式之间切换,以了解哪种感觉更好。

享受Python中的分析仪表板 (Enjoy analytics dashboard in Python)

Congratulations! Excellent work. We’ve brought our data to life. Now you have a powerful Django application enabled with reporting and data visualization functionality.

恭喜你! 优秀作品。 我们将数据变为现实。 现在,您已经拥有一个功能强大的Django应用程序,该应用程序 具有报告数据可视化功能。

The thing your end-users may find extremely comfy is that it’s possible to configure a report, save it, and pick up where you left off later by uploading it into the pivot table. Reports are neat JSON files that can be stored locally or to the server. Also, it’s possible to export reports into PDF, HTML, Image, or Excel files.

最终用户可能会感到非常自在的是,可以配置报告,保存报告,然后将报告上载到数据透视表中,以选择您上次中断的地方。 报表是可以存储在本地或服务器上的纯净JSON文件。 此外,还可以将报告导出为PDFHTMLImageExcel文件。

Feel free to tailor the app according to your business requirements! You can add more complex logic, change the data source (e.g., MySQL, PostgreSQL, Oracle, Microsoft Analysis Services, Elasticsearch, etc), and customize the appearance and/or the functionality of the pivot table and pivot charts.

可以根据您的业务需求随意定制应用程序! 您可以添加更复杂的逻辑,更改数据源 (例如MySQLPostgreSQLOracleMicrosoft Analysis ServicesElasticsearch等),以及自定义数据透视表和数据透视表的外观和/或功能。

进一步阅读 (Further reading)

额外设置以美化您的报告 (Extra settings to prettify your report)

Here's an additional section for curious minds!

这是一个针对好奇心的附加部分!

To prettify the hierarchies’ captions and define field types, we’ll add mapping - a special object in the data source configuration of the report. Mapping helps us define how to display field names by setting captions. Plus, it’s possible to explicitly define types of fields (numbers, strings, different types of dates). Every piece of configuration depends on your business logic.

为了美化层次结构的标题并定义字段类型,我们将添加映射 -报表数据源配置中的一个特殊对象。 映射帮助我们通过设置标题来定义如何显示字段名称。 另外,可以显式定义字段的类型(数字,字符串,不同类型的日期)。 每项配置都取决于您的业务逻辑。

Generally speaking, mapping creates an additional level of abstraction between the data source and its representation.

一般而言,映射在数据源及其表示之间创建了更高的抽象级别。

Here’s an example of how it can be defined for the retail dataset:

这是一个如何为零售数据集定义的示例:

"mapping": {
    "InvoiceNo": {
        "caption": "Invoice Number",
        "type": "string"
    },
    "StockCode": {
        "caption": "Stock Code",
        "type": "string"
    },
    "Description": {
        "type": "string"
    },
    "Quantity": {
        "type": "number"
    },
    "InvoiceDate": {
        "type": "string",
        "caption": "Invoice Date"
    },
    "UnitPrice": {
        "type": "number",
        "caption": "Unit Price"
    },
    "CustomerID": {
        "type": "string",
        "caption": "Customer ID"
    },
    "Country": {
        "type": "string"
    }
}

翻译自: https://www.freecodecamp.org/news/how-to-build-a-web-based-dashboard-with-django-mongodb-and-pivot-table/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值