什么是在Django中筛选模型并将其显示为表格的好方法?

huangapple go评论74阅读模式
英文:

What is a good way to filter a model and display that as a table in Django?

问题

I have been struggling on finding a simple method for displaying a filtered model on a Django webpage. I am using DataTables for my tables.

Here is some code for my view that filters a value and creates a serialized JSON. I am not sure of another method to do this, but intuitively it made sense to transform the filtered model and send it over to the webpage in the 'context' parameter.

def site(request, site_name):

    filtered = Participant.objects.filter(site_name=site_name).all()
    serialized = json.loads(serialize('json', filtered))

    return render(request, 'site.html', context={'site': site_name, 'filtered': serialized})

Here's my JavaScript:

$(document).ready(function() {
    $('#my-table').DataTable( {
        data: JSON.parse(filteredData),
        lengthMenu: [[25, 50, 100, -1], [25, 50, 100, "All"]],
        pageLength:  50,
        responsive: true,
        processing: true,
        serverSide: false,
        bSearchable: true,

        columns: [
             {"data": "some_data"},
        ],
      
    } );
} );

And here's where I pass in the filteredData variable in my HTML:

<script>
    filteredData = "{{filtered}}"
</script>

This does not work as I am not really sure how DataTables handles JSON files. I presume that the solution is simple, but I am quite new to Django. Thank you!

英文:

I have been struggling on finding a simple method for displaying a filtered model on a Django webpage. I am using DataTables for my tables.

Here is some code for my view that filters a value and creates a serialized json. I am not sure of another method to do this, but intuitively it made sense to transform the filtered model and send it over to the webpage in the 'context' parameter.

def site(request, site_name):

    filtered = Participant.objects.filter(site_name=site_name).all()
    serialized = json.loads(serialize(&#39;json&#39;, filtered))

    return render(request, &#39;site.html&#39;, context={&#39;site&#39;: site_name, &#39;filtered&#39;: serialized})

Here's my javascript:

$(document).ready(function() {
    $(&#39;#my-table&#39;).DataTable( {
        data: JSON.parse(filteredData),
        lengthMenu: [[25, 50, 100, -1], [25, 50, 100, &quot;All&quot;]],
        pageLength:  50,
        responsive: true,
        processing: true,
        serverSide: false,
        bSearchable: true,

        columns: [
             {&quot;data&quot;: &quot;some_data&quot;},
        ],
      
    } );
} );

And here's where I pass the in the filteredData variable in my HTML:

&lt;script&gt;
    filteredData = &quot;{{filtered}}&quot;
&lt;/script&gt;

This does not work as I am not really sure how DataTables handles JSON files. I presume that the solution is simple, but I am quite new to Django. Thank you!

答案1

得分: 1

I was able to solve it! The serialized JSON that is generated from serializing a filtered model is not the correct format. I had to change my booleans to strings before I passed the JSON string to my site. I could have also changed the booleans to lowercase (e.g., False -> false) since JavaScript syntax is uncapitalized unlike Python.

def site(request, site_name):

    site_pguids = Participant.objects.filter(site_name=site_name).all()
    serialized = str(json.loads(serialize('json', site_pguids)))
    serialized = serialized.replace("False", "'False'")
    serialized = serialized.replace("True", "'True'")

    return render(request, 'site.html', context={'site': site_name, 'filtered': serialized})

Then, in my JavaScript, I simply replaced the single quotes with double quotes and it worked.

data: JSON.parse(filteredData.replace(/&#39;/g, '&quot;')),
英文:

I was able to solve it! The serialized JSON that is generated from serializing a filtered model is not the correct format. I had to change my booleans to strings before I passed the JSON string to my site. I could have also changed the booleans to lowercase (e.g., False -> false) since JavaScript syntax is uncapitalized unlike Python.

def site(request, site_name):

    site_pguids = Participant.objects.filter(site_name=site_name).all()
    serialized = str(json.loads(serialize(&#39;json&#39;, site_pguids)))
    serialized = serialized.replace(&quot;False&quot;, &quot;&#39;False&#39;&quot;)
    serialized = serialized.replace(&quot;True&quot;, &quot;&#39;True&#39;&quot;)

    return render(request, &#39;site.html&#39;, context={&#39;site&#39;: site_name, &#39;filtered&#39;: serialized})

Then, in my JavaScript I simply replaced the single quotes with double quotes and it worked.

data: JSON.parse(filteredData.replace(/&#39;/g, &#39;&quot;&#39;)),

答案2

得分: 0

以下是翻译好的部分:


JSON 数据

您的 JSON 字符串如下(基于另一个回答中的注释):

[{
	"model": "participants.participant",
	"pk": 5533,
	"fields": {
		"pGUID": "somedata",
		"site_name": "somedata",
		"fb_email": "somedata",
		"is_authorized": false
	}
}]

请注意使用的是双引号而不是单引号。请注意使用 false 而不是 False


JavaScript 部分

如果您将其写成字符串,您需要得到以下 JavaScript:

var filteredData = '[{"model": "participants.participant","pk": 5533,"fields": {"pGUID": "somedata","site_name": "somedata","fb_email": "somedata","is_authorized": false}}]';

请注意整个字符串都用单引号括起来,以不干扰 JSON 本身内部的双引号。

因此,您需要确保您的 JavaScript 占位符如下:

filteredData = '{{filtered}}';

我无法评论您在 Django 应用程序中创建 {{filtered}} 字符串的最佳方法。抱歉,我不使用 Django。


演示

但是,一旦您将该字符串正确传递到您的网页,然后您可以按如下方式使用它。在以下演示中,我只是硬编码了字符串,而不是使用 {{filtered}}

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

/*
what the json should look like:
[{
	"model": "participants.participant",
	"pk": 5533,
	"fields": {
		"pGUID": "somedata",
		"site_name": "somedata",
		"fb_email": "somedata",
		"is_authorized": false
	}
}]

// your JSON as a string, provided by Django:
var filteredData = '[{"model": "participants.participant","pk": 5533,"fields": {"pGUID": "somedata","site_name": "somedata","fb_email": "somedata","is_authorized": false}}]';

$(document).ready(function() {
  $('#my-table').DataTable({
    data: JSON.parse(filteredData),
    lengthMenu: [
      [25, 50, 100, -1],
      [25, 50, 100, "All"]
    ],
    pageLength: 50,
    responsive: true,
    processing: true,
    serverSide: false,
    searchable: true,

    columns: [{
        data: "model",
        title: "Model"
      },
      {
        data: "fields.pGUID",
        title: "GUID"
      },
      {
        data: "fields.is_authorized",
        title: "Authorized?"
      }
    ],
  });
});

<!-- language: lang-html -->

<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Demo</title>
  <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
  <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">

</head>

<body>

  <div style="margin: 20px;">

    <table id="my-table" class="display dataTable cell-border" style="width:100%;">
    </table>

  </div>

</body>

</html>

<!-- end snippet -->

在上面的代码中,您可以看到如何引用 JSON 中的不同字段:

data: "model"
data: "fields.pGUID"
data: "fields.is_authorized"

...等等。

我还添加了 title 选项,以为您的表格添加一些标题。


另一种方法

我更喜欢的方法是在 Django 中有一个端点,该端点提供正确的 JSON(而不是字符串)并直接使用Ajax 数据源将其提供给 DataTable。

但是,考虑到您的起点,这可能需要更多的工作。

您的方法当然没有问题 - 这是个人偏好的问题。因此,也许先让您当前的方法运行起来,然后再决定是否要尝试不同的方法。

英文:

Given your starting point, the least amount of work for you is probably as follows:


The JSON Data

Your JSON string is as follows (based on a comment in another answer):

&quot;[{&#39;model&#39;: &#39;participants.participant&#39;, &#39;pk&#39;: 5533, &#39;fields&#39;: {&#39;pGUID&#39;: &#39;somedata&#39;, &#39;site_name&#39;: &#39;somedata&#39;, &#39;fb_email&#39;: &#39;somedata&#39;, &#39;is_authorized&#39;: False}}]&quot;

But that is not a string containing valid JSON.

Valid JSON would be this:

[{
	&quot;model&quot;: &quot;participants.participant&quot;,
	&quot;pk&quot;: 5533,
	&quot;fields&quot;: {
		&quot;pGUID&quot;: &quot;somedata&quot;,
		&quot;site_name&quot;: &quot;somedata&quot;,
		&quot;fb_email&quot;: &quot;somedata&quot;,
		&quot;is_authorized&quot;: false
	}
}]

Note the use of double-quotes - not single quotes. Note the use of false not False.


The JavaScript

If you write this as a string, you need to end up with the following JavaScript:

var filteredData  = &#39;[{&quot;model&quot;: &quot;participants.participant&quot;,&quot;pk&quot;: 5533,&quot;fields&quot;: {&quot;pGUID&quot;: &quot;somedata&quot;,&quot;site_name&quot;: &quot;somedata&quot;,&quot;fb_email&quot;: &quot;somedata&quot;,&quot;is_authorized&quot;: false}}]&#39;

Note that the entire string is enclosed in single quotes, so as to not interfere with the double-quotes inside the JSON itself.

You therefore need to ensure your JavaScript placeholder is this:

filteredData = &#39;{{filtered}}&#39;;

I can't comment on the best way for you to create that {{filtered}} string in your Django app. Sorry, I don't use Django.


A Demo

But once you have that string correctly passed to your web page, then you can use it as follows. In the following demo, I have just hard coded the string, instead of using {{filtered}}:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

/*
what the json should look like:
[{
	&quot;model&quot;: &quot;participants.participant&quot;,
	&quot;pk&quot;: 5533,
	&quot;fields&quot;: {
		&quot;pGUID&quot;: &quot;somedata&quot;,
		&quot;site_name&quot;: &quot;somedata&quot;,
		&quot;fb_email&quot;: &quot;somedata&quot;,
		&quot;is_authorized&quot;: false
	}
}]
*/

// your JSON as a string, provided by Django:
var filteredData = &#39;[{&quot;model&quot;: &quot;participants.participant&quot;,&quot;pk&quot;: 5533,&quot;fields&quot;: {&quot;pGUID&quot;: &quot;somedata&quot;,&quot;site_name&quot;: &quot;somedata&quot;,&quot;fb_email&quot;: &quot;somedata&quot;,&quot;is_authorized&quot;: false}}]&#39;;

$(document).ready(function() {
  $(&#39;#my-table&#39;).DataTable({
    data: JSON.parse(filteredData),
    lengthMenu: [
      [25, 50, 100, -1],
      [25, 50, 100, &quot;All&quot;]
    ],
    pageLength: 50,
    responsive: true,
    processing: true,
    serverSide: false,
    searchable: true,

    columns: [{
        data: &quot;model&quot;,
        title: &quot;Model&quot;
      },
      {
        data: &quot;fields.pGUID&quot;,
        title: &quot;GUID&quot;
      },
      {
        data: &quot;fields.is_authorized&quot;,
        title: &quot;Authorized?&quot;
      }
    ],
  });
});

<!-- language: lang-html -->

&lt;!doctype html&gt;
&lt;html&gt;

&lt;head&gt;
  &lt;meta charset=&quot;UTF-8&quot;&gt;
  &lt;title&gt;Demo&lt;/title&gt;
  &lt;script src=&quot;https://code.jquery.com/jquery-3.5.1.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;https://cdn.datatables.net/1.10.22/js/jquery.dataTables.js&quot;&gt;&lt;/script&gt;
  &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;https://cdn.datatables.net/1.10.22/css/jquery.dataTables.css&quot;&gt;
  &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;https://datatables.net/media/css/site-examples.css&quot;&gt;

&lt;/head&gt;

&lt;body&gt;

  &lt;div style=&quot;margin: 20px;&quot;&gt;

    &lt;table id=&quot;my-table&quot; class=&quot;display dataTable cell-border&quot; style=&quot;width:100%&quot;&gt;
    &lt;/table&gt;

  &lt;/div&gt;



&lt;/body&gt;

&lt;/html&gt;

<!-- end snippet -->

In the above code, you can see how to refer to the different fields in your JSON:

data: &quot;model&quot;
data: &quot;fields.pGUID&quot;
data: &quot;fields.is_authorized&quot;

...and so on.

I added the title options as well, to give your table some headers.


An Alternative

I would prefer the approach where you have a Django endpoint which serves the correct JSON (as JSON, not as a string) and provides that directly to the DataTable using an Ajax data source.

But that is probably more work, given your starting point.

There is certainly nothing wrong with your approach - it's a matter of preference. So, maybe get your current approach working first, and then decide if you want to try a different approach, after that.

huangapple
  • 本文由 发表于 2023年5月18日 09:03:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76277113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定