是否有可能在烧瓶炼金术中返回分组行?

时间:2015-08-18 20:06:12

标签: python sqlalchemy flask-sqlalchemy

我试图找回基于特定列分组的行,但我不确定flask-sqlalchemy是否可以返回这样的内容。一个简单的例子:

# Models
class User(Model):
  id = Column(Integer, primary_key=True)
  name = Column(String, default="foobar")
  items = relationship("Item", backref="user", lazy="dynamic")

class Item(Model):
   id = Column(Integer, primary_key=True)
   name = Column(String, default="")
   custom_name = Column(String, default="default")
   owner_id = Column(Integer, ForeignKey('user.id'))

示例数据表是:

# Users
id   name 
-------------
1    Bob
2    Alice

# Items
id    name    custom_name    owner_id
--------------------------------------
1     book1   reading_list   1
2     book2   reading_list   1
3     teapot  kitchen_thing  2
4     tv      entertainment  1
5     pc      entertainment  2

我想要所有Bob个项目,但会根据custom_name进行分组。最终结果是在jinja2模板上按custom_name显示数据:

# Somewhere in flask
@app.route("/mylist")
def mylist():
    # get all items belong to Bob
    grouped_items = Item.query.filter_by(owner_id = 1 ).... # then chain the result to somehow group by custom_name ?

    return render_template("mylist.html", grouped_items=grouped_items)

然后我想基于custom_name

呈现它
<!-- mylist.html  ...in pseudocode!... -->

{% for group in grouped_items %}
    <span>Item Custom name: {{ group.custom_name }}</span>
    {% for item in group %}
        <span>{{ item.name }}</span>
    {% endfor %}
{% endfor %}

最终应该是:

Item Custom name: reading_list
    book1
    book2
Item Custom name: entertainment
    tv

我知道我可以创建自己的字典,其中custom_name为关键字,值为具有该自定义名称的项目列表,但我想知道这种分组是否可以直接从烧瓶中进行 - sqlalchemy而不是手动循环查询结果来构建字典?

0 个答案:

没有答案