2016-05-12 4 views
1

質問テンプレートにredis jsonデータを表示するにはどうすればよいですか?何らかの理由で私はそれを働かせることができません。どんな助けも大いに評価されるでしょう。私のテンプレートビューでredis jsonデータを表示する方法python django

これまでの私のjsonデータは正しくredisに保存されていますが、それでも私のテンプレートに表示する方法は分かりません。だからobj.customer_name私はredisから来て、私のテンプレートのjsonデータを反復したい。

views.py

def home(request): 
    """Renders the home page.""" 
    assert isinstance(request, HttpRequest) 
    #obj = Customer.objects.all() 
    cust = Customer.objects.all() 
    da = serializers.serialize('json', cust, fields=('customer_id', 'customer_name')) 
    r_conn = redis.StrictRedis(host='172.16.1.98', port=6379, db=1) 
    r_conn.set('dimcert_cust', da) 
    cust_cache = r_conn.get('dimcert_cust') 
    obj = json.load(cust_cache) 


    return render(
     request, 
     'app/index.html', 
     { 
      'title':'Home Page', 
      'year':datetime.now().year, 
      'obj': obj, 
     } 
    ) 

home.htmlテンプレート

ここ
{% extends "app/layout.html" %} 

{% block content %} 

<div class="jumbotron"> 
    <h1>Customers</h1> 
</div> 

<div class="row"> 


    <div style="width: 40%; float:left"> 
     {% for obj in obj.all %} 
      <h3> {{obj.customer_name}} </h3> 
     {% endfor %} 

    </div>  
</div> 

{% endblock %} 

あるCustomerクラスと私のmodel.py

from django.db import models 
import json 

class Customer(models.Model): 
    objects = models.Manager() 
    customer_id = models.IntegerField() 
    customer_name = models.CharField(max_length=255) 
    created_at = models.DateField 
    updated_at = models.DateField 

答えて

2

あなたがして辞書にJSONを変換しますobj = json.load(cust_cache)あなたのテンプレートでは、あなたが持っているべきものは次のようなものです:

{% for key, values in obj.items %} 

    <h3>{{ key }}</h3> 
    {{ value }} 
{% endfor %} 

脚注として、私はredis hashesがあなたのデータを保存するより良い方法であると指摘してもよいでしょうか。

+0

ありがとうございました! @ e4c5 – Snowman08

+0

助けてくれてうれしいです。 – e4c5

関連する問題