假设我有一个名为app.controller('captureCtrl',[ '$scope', 'captureApi', 'auth', '$http', '$timeout', 'filepickerService',
function($scope, captureApi, auth, $http, $timeout, filepickerService){
$scope.form = {};
$scope.auth = auth;
$scope.upload = function(){
filepickerService.pick(
{
mimetype: 'image/*',
language: 'en',
services: ['COMPUTER','DROPBOX','GOOGLE_DRIVE', 'FACEBOOK', 'INSTAGRAM'],
openTo: 'COMPUTER'
},
function(Blob){
console.log(JSON.stringify(Blob));
$scope.capture = {};
$scope.capture.picture = Blob;
$scope.$apply();
}
);
};
$scope.addToDatabase = function(){
$scope.form = {};
var dataObj = {
birdname: $scope.birdname,
place : $scope.place,
userId : $scope.auth.profile.user_id,
author : $scope.auth.profile.name,
picture: $scope.capture.picture.url
};
$scope.captureMessage = true;
captureApi.insertCapture(dataObj)
$scope.birdname = "";
$scope.place = "";
$timeout(function() {
$scope.captureMessage = false;
}, 3000);
};
}]);
的表,当我想知道person
的记录是否存在时,我将尝试以下代码
id=1
问题是,如果if Person.query.filter_by(id = 1).count() > 0:
do_something()
没有记录,id=1
只会抛出flask-sqlalchemy
而不是返回0.这是否意味着OperationalError
捕获count
时为0?换句话说,我应该按以下方式进行:
OperationalError
对我来说,它似乎并不是一种优雅的方式。那么有没有更好的方法来实现它?
答案 0 :(得分:2)
您不需要使用count
来检查它是否存在。你可以这样做:
if Person.query.get(1):
do something()
如果没有None
的记录,它将返回id=1
。对于其他条件:
# filter_by(name='Nancy') for example
if Person.query.filter_by(id=1).first():
do something()
答案 1 :(得分:0)
更简单的方法是
from sqlalchemy.sql import exists
if if session.query(exists().where(Person.id == 1)).scalar() is not None: #check if id=1 exists
do_something_when_record_exists()
else:#else run when no record is present
do_something_when_theres_no_record()
other_code()#run it anyway
答案 2 :(得分:0)
事实证明,数据库与我的模型不一致,我删除了数据库并重新创建了表,然后一切正常。
如果一切正常,Person.query.filter_by(id = 1).count()
应该返回0
如果没有记录则会引发错误。