在Pymongo中创建集合之间的关系并将其渲染为Jinja

时间:2018-05-14 13:34:55

标签: mongodb python-2.7 flask jinja2 pymongo

考虑下面的图像。我在MongoDB中有两个集合,我想通过匹配它应该给我所需输出的名称来渲染结果。

我的问题是,当我尝试编码时,我无法建立关系:

{% for i in new %}
    <h4 class>New Price - {{ i.Product }}</h4>
        {% for z in Preowned %}
            {% if z['Product'] == i.Product %}
            <h4 class>Preowned Price - {{z.Price}}</h4>
            {%endif %}
{% endfor %}
{% endfor %}

我真的被困在这里,不知道如何处理这个问题。如果您有我的问题的替代解决方案,请帮助。

enter image description here

2 个答案:

答案 0 :(得分:1)

我尽可能简单地回答你的问题,让你理解它。你可以尝试测试一下。

app.py

@app.route('/test')
def test():
    New = db.New.find().sort('Product', 1)
    Preowned = db.Preowned.find().sort('Product', 1)
    return render_template('test.html',
                           NP=zip(list(New), list(Preowned)))

NP = zip(列表(新),列表(Preowned))

[

({'_id': ObjectId('5af9bd331f2d0f3b97f57ee3'), 'Product': 'Adidas', 'Price': 2000, 'Platform': 'Shoes'},
{'_id': ObjectId('5af9bda51f2d0f3b97f57f1c'), 'Product': 'Adidas', 'Price': 1000, 'Platform': 'Shoes'}),

({'_id': ObjectId('5af9bd601f2d0f3b97f57efd'), 'Product': 'Fila', 'Price': 2400, 'Platform': 'Shoes'},
{'_id': ObjectId('5af9bdcb1f2d0f3b97f57f2b'), 'Product': 'Fila', 'Price': 400, 'Platform': 'Shoes'}),

({'_id': ObjectId('5af9bd751f2d0f3b97f57f05'), 'Product': 'Puma', 'Price': 700, 'Platform': 'Shoes'},
{'_id': ObjectId('5af9bdd91f2d0f3b97f57f33'), 'Product': 'Puma', 'Price': 400, 'Platform': 'Shoes'}),

({'_id': ObjectId('5af9bd4f1f2d0f3b97f57ef4'), 'Product': 'Sneakers', 'Price': 1600, 'Platform': 'Shoes'},
{'_id': ObjectId('5af9bdbd1f2d0f3b97f57f27'), 'Product': 'Sneakers', 'Price': 600, 'Platform': 'Shoes'})

]

的test.html

{% for n, p in NP %}
    {% if n.Product == p.Product %}
        <h4>{{n.Product}} {{n.Platform}}</h4>
        <h4>Buy Now - New : {{n.Price}}</h4>
        <h4>Buy Now - Preowned : {{p.Price}}</h4>
        <br>
    {% endif %}
{% endfor %}

结果

Adidas Shoes
Buy Now - New : 2000
Buy Now - Preowned : 1000

Sneakers Shoes
Buy Now - New : 1600
Buy Now - Preowned : 600

Fila Shoes
Buy Now - New : 2400
Buy Now - Preowned : 400

Puma Shoes
Buy Now - New : 700
Buy Now - Preowned : 400

答案 1 :(得分:1)

您可以编写一个聚合查询,其lookup stage执行左外连接到其他一些集合。 请注意此功能是在Mongo 3.2中引入的。

假设这两个集合都是collection1&amp; collection2,然后从图表中提取,您的查询将如下所示:

pipeline = [
    {
        '$lookup': {
            'from': 'collection2',
            'localField': 'Product',
            'foreignField': 'Product',
            'as': 'Matches'
        }
    }
]

db.collection1.aggregate(pipeline)

在Jinja,你可以写:

{% for new_item in new_items %}
    <h4>New Price - {{ new_item.Product }}</h4>
    {% for preowned in new_item.Matches %}
        <h4>Preowned Price - {{ preowned.Price }}</h4>
    {% endfor %}
{% endfor %}