【问题标题】:Django: displaying a dynamic raw queryDjango:显示动态原始查询
【发布时间】:2012-11-09 02:19:24
【问题描述】:

我有一个按类型过滤的查询,“水果”

水果 = { 苹果、橙子、芒果、菠萝等 }

但是在这种情况下,每种水果也有不同的物品。 (对于开发人员:服务器内域的属性)

http://i46.tinypic.com/35kj1o7.png

注意: - 水果的种类会因天而异,有些水果不是当季水果。 - 对于开发人员:各个服务器可能拥有不同数量的域 - numType 字段动态确定当天有多少不同的“水果”可供使用

主要目标: - 在表格中显示和排序可用数据。

http://i48.tinypic.com/infhip.png

在 view.py 上,我做了 2 个原始 sql 查询

  1. 从 main where cat =='fruit' 中选择 *
  2. Select * from main where cat =='fruit' && name='numType'

提前致谢!

【问题讨论】:

    标签: django templates loops


    【解决方案1】:

    不确定我是否完全遵循了这个问题,但请尝试查看Django template for loops 上的文档,您可以使用该标签遍历键/值对。

    如果比这更复杂,你能试着多解释一下吗?


    也许regroup 会满足您的需求?

    {% regroup fruit_list by [key] as apple_list %}
    
    {% for apples in apple_list %}
        <table>
        {% for apple in apples %}
        <td>{{apple}}</td>
        {% endfor %}
        </table>
    {% endfor %}
    

    【讨论】:

    • edit:在我看来,我从 render_to_response 传递fruit_list 我希望将列表中的项目放入不同的表中,具体取决于它们是 apples.1 还是 apples.2 。我不能在视图中这样做,因为 apples.1 apples.2 的数量不一致
    【解决方案2】:

    我可能错了,可能有更好的方法,欢迎大家分享和讨论。

    当前缺陷:dicts 是无序的

    在我看来.py:

    • 我做了两个查询,

      1. fruit_list = select * from main where type ="fruit"

      //这会告诉我当天出售的水果种类

      1. number_of_cat = 从 main where type ="fruit" and name="numType" 中选择价格
    • // 将 django 返回的查询集转换为列表 fruitRows = list(fruit_list)

    • lenRow = len(fruitRows)

    • //在python中创建一个dict masterFruitList = {};

    • // 根据数量在dict中创建键 对于我在范围内(int(number_of_cat)): masterFruitList['fruit_Type'+ str(i+1)] = []

    • //向字典添加行

    • // 添加到上下文 return render_to_response('data.html', {'numdo' : masterFruitList })

    模板.html:

    重点是使用.items语法来迭代python字典

    {% if numdo %}
        {% for key,value in numdo.items %}
             <p> hey! <b> {{ key }} </b>
                <table class = "tablebord">
                    <tr>
                        <th> name </th>
                        <th> type </th>
                        <th> price </th>
                    </tr>
                    {% for x in value %}
                        <td class = "tablebord"> {{ x.name }} </td>
                        <td class = "tablebord"> {{ x.type }} </td>
                        <td class = "tablebord"> {{ x.price }} </td>
                    </tr>
                    {% endfor %}
                </table>
             </p>
    
        {% endfor %}
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 2020-01-02
      • 2015-11-21
      • 2012-03-16
      • 2020-05-20
      • 1970-01-01
      • 2018-05-15
      • 2015-05-01
      • 2013-04-17
      • 2021-09-23
      相关资源
      最近更新 更多