我尝试使用SQLAlchemy方法load_only并推迟仅从数据库发送某些列,但是我似乎无法使它们正常工作。
这是我正在使用的代码:
query = db.session.query(Vendor).options(defer('ownerName', 'boxSize', 'boxes', 'lastPickUp', 'zone', 'code')) return response( query )
我期待得到答复:
{ “回复”: [ { "address": "10th and SW Alder St", "city": "Portland, OR", "id": 1, "keywords": "Tacos, Mexican", "latitude": 45.5206464, "longitude": -122.68157559999997, "name": "Taco Ted", "phone": null, "website": null, }, …
{
“回复”: [
{ "address": "10th and SW Alder St", "city": "Portland, OR", "id": 1, "keywords": "Tacos, Mexican", "latitude": 45.5206464, "longitude": -122.68157559999997, "name": "Taco Ted", "phone": null, "website": null, },
…
但是相反,我得到了:
{ “回复”: [ { "address": "10th and SW Alder St", "boxSize": null, "boxes": 10, "city": "Portland, OR", "id": 1, "keywords": "Tacos, Mexican", "lastPickUp": "01/12/2014", "latitude": 45.5206464, "longitude": -122.68157559999997, "name": "Taco Ted", "ownerName": null, "phone": null, "website": null, "zone": 1 }, …
{ "address": "10th and SW Alder St", "boxSize": null, "boxes": 10, "city": "Portland, OR", "id": 1, "keywords": "Tacos, Mexican", "lastPickUp": "01/12/2014", "latitude": 45.5206464, "longitude": -122.68157559999997, "name": "Taco Ted", "ownerName": null, "phone": null, "website": null, "zone": 1 },
这意味着我的延期将被忽略。我也尝试过使用load_only来解决此问题,但是它们似乎没有什么区别。我在这里想念什么?
(如果有什么不同,我正在使用sqlite数据库进行开发。)
那不是正确的用法,deferred()这里load_only()添加的用例就是为什么要添加。每个调用一次deferred()仅具有一个属性;它接受许多字符串的事实与查询中的“路径”有关,这与您在此处所处理的无关。
deferred()
load_only()
load_only()将防止未命名的属性在初始查询中加载:
load_only('ownerName', 'boxSize', 'boxes', 'lastPickUp', 'zone', 'code')
但是,如果您的jsonify方法仍然调用这些属性(例如)somevendor.boxSize,它将在此时发出SQL。因此,这还取决于您如何拉动属性。
somevendor.boxSize