22824

Compare difference between two columns in SQLAlchemy ORM

<h3>Question</h3>

I'm trying to find out how to do something like the answer to this question but using SQLAlchemy.

Having a hard time finding how to order query results by the difference between two columns without resorting to raw SQL.

Any help is greatly appreciated!!

Also, just out of curiosity, is it possible to create a column that automatically calculates the difference between two other columns? For example, you would have a revenue and loss column, and then a profit column that automatically combined those.


<h3>Answer1:</h3>
session.query((Table.revenue - Table.loss).label('profit')).order_by('profit desc').all()

For automatically calculate column you can use events

from sqlalchemy import event class Table(Model): id = Column(Integer, primary_key=True) revenue = Column(Integer) loss = Column(Integer) profit = Column(Integer) @event.listens_for(Table.revenue, 'set') def revenue_listener(target, value, oldvalue, initiator): # update profit when revenue change target.profit = value - (target.loss or 0) @event.listens_for(Table.loss, 'set') def loss_listener(target, value, oldvalue, initiator): # update profit when loss change target.profit = (target.revenue or 0) - value

来源:https://stackoverflow.com/questions/33505946/compare-difference-between-two-columns-in-sqlalchemy-orm

Recommend

  • Display and update FormGroup inside FormArray
  • Is it possible to disable the Daemon started by default when starting Android Studio?
  • must declare a named package eclipse because this compilation unit is associated to the named module
  • must declare a named package eclipse because this compilation unit is associated to the named module
  • Filtering a list using Java 8 lambda expressions
  • Q: Simple-Salesforce make a dynamic soql query
  • How to upgrade NuGet with Visual Studio 2017?
  • Java Mandelbrot visualization questions on zooming and coloring
  • How can I know when the Enter key was pressed on QTextEdit
  • Windows cmd doesn't recognize python or pip after installing mysql
  • How to get the url of the newly opened tab using Javascript?
  • How to get the url of the newly opened tab using Javascript?
  • Get the index of the face pointing up of SCNNode
  • Expo Tunnel not starting
  • Is it possible to create a macro, that will create a hyperlink, that will run a macro
  • getActiveSpreadsheet() always returns null
  • getActiveSpreadsheet() always returns null
  • How to set role-based login for jenkins in keycloak
  • How to set role-based login for jenkins in keycloak
  • How to set role-based login for jenkins in keycloak
  • How to set role-based login for jenkins in keycloak
  • Can't Move Tab to Desired Position
  • arrays TP, TN, FP and FN in Python
  • How to switch windows within PeekView window without mouse
  • How to switch windows within PeekView window without mouse
  • SortableJS get order from nested list
  • How to switch windows within PeekView window without mouse
  • Python: How to encode DNA sequence using binary values?
  • Flask is not finding folders and files in Python
  • Bison : Line number included in the error messages
  • TCP协议
  • if my table has 4 colums and i want to fetch the 3rd column what do i do.
  • Add boundaries to an SKScene
  • How to remove space after the first pattern in sed
  • During XGrabKey(board), discover which window had been focused
  • E/unknown:React: Exception in native call
  • Auto postBack in MVC4 razor page
  • Specifying Google perftools to g++ for using C++ in R
  • PyPDF2 compression
  • Can't receive FCM Push Notifications for iOS
  • custom button always too big
  • in c++ how do I return an array of objects from a function?
  • Error while creating tables dynamically in R shiny
  • Objective C send data to phonegap and call javascript function
  • Flexbox For Equal height columns and row (equalizer)
  • How to create and manage a nested TabbedViewNavigator?
  • Convert rtsp-stream into http stream
  • Fixed sidebar and fluid content area
  • Button click counter in JavaScript
  • String to Date conversion (everything seems good but fail)
  • Getting Http “ERROR 500” with symfony4 using byethost
  • AWS EC2 Could not open a connection to SQL Server
  • Using AES in CBC with the same IV for messages
  • Centering an image in UIAlertAction in UIAlertController
  • How to convince ocaml that two functor instantiations are equal
  • Google Cloud Dataflow Python, Retrieving Job ID
  • How to read json file using python pandas?
  • How can I extract an area weighted sum from a raster into a polygon in R?
  • Fancybox jQuery: iframe vs ajax
  • Why does a PendingIntent trigger onCreate even though FLAG_NO_CREATE is set
  • disable pinch recognizer when 1 finger is lifted on the screen
  • Visual Studio “if” snippet initially won't recognize variables
  • Change Tab Bar icon/text tint color from Storyboard
  • How do I programmatically assign a on click event to a bullet list which was programmatically create
  • Fold up a Layout but keep another at the bottom
  • How to make vertical tabs with React
  • Compatibility of Eclipse Luna with SVN 1.6
  • How to deploy a website on Heroku?
  • What is the default password for SQL Server 2012 if I didn't put a password in the setup?
  • SCNNode Z-rotation axis stays constant, while X and Y axes change when node is rotated
  • Subscript out of bound error in R
  • admob only sends test ad not real ads
  • Why is the array empty every time on click?
  • Valid characters for file name in the #include directive
  • How to put constrains on maximum selectable CheckBoxes via RadioButtons in JavaFX?
  • Jupyter Notebook kernel dies when importing tensorflow 1.5.0
  • JQuery UI Tabs with AJAX content VERY slow using IE9
  • Stop JSF Event Chain
  • IE8 does not submit hidden input in form
  • Formatting Date for Postgresql
  • TabLayout not show icon with android support library 23.2.0
  • jQuery click _blank
  • How to run a chrome extension as a web socket server?
  • Python translate with multiple characters
  • Publish ARM templates in azure portal
  • use edit distance on arrays in perl
  • How to create an abstract base class in python which derived from QObject
  • Azure keys for Luis not available
  • Using nuxt, how do I put the route name in the page title?
  • IdentityServer4 how to set server cookie expiration
  • Fetch api issue with DELETE - changes to OPTIONS even when cors is good
  • Android app communication with web server?
  • Violation of the Permissions policy in google play
  • Kafka Spring: How to create Listeners dynamically or in a loop?
  • sessionStorage changes aren't firing 'storage' event
  • Android internet permission ignored
  • How to load an XHTML file into an XElement using a custom XmlUrlResolver?
  • Display custom tag in google maps infowindow angular2
  • how to find the number of maximum available threads in CUDA?
  • Error while evaluating the function convolution
  • openDocAsReadonly Computed?
  • Porting C++ Project to Android
  • How to disable labelname.tabindex?
  • Search value in body tag in Sitecore
  • How to post to other domain and get result html in javascript
  • ORB_SLAM installation on Ubuntu Xenial 16.04
  • Tab panels swipe-able in mobile view?
  • What is the full list of provider id's for firebase.UserInfo.providerId?
  • Why do I get java.lang.UnsatisfiedLinkError: Unable to load library?
  • Prevent popup.html of Chrome from being closed by iframe action
  • Karaf exception is thrown while installing org.fusesource.leveldbjni
  • Make Tkinter Notebook be Draggable to Another View
  • How to set source IP to http request?
  • npm ERR! fatal: Unable to find remote helper for 'https'
  • 梳理commons-lang工具包
  • 网络协议 17 - HTTPDNS
  • How to add a JAR file to an existing gradle project?
  • Is it possible to serialize sprites in unity?
  • Angular Service Worker, caching api calls for offline app
  • Probable instruction Cache Synchronization issue in self modifying code?
  • Change AcroFields order in existing PDF with iText?
  • How do __getitem__, __setitem__, work with slices?
  • Active Admin - Same model for users and admins
  • how to convert anonymous type to known type
  • How to change keybindings of atom
  • Separate ResourceDictionary for each project type
  • How to disconnect Windows Phone 8.1 emulator from network?
  • Keep MKMapSnapshotter as NSData in memory - Swift
  • HTTPS page was not allowed to run insecure content from safari-extension:// URI
  • Doctrine partial queries return the complete object
  • grunt: command not found
  • chrome extension - best method of reducing load time while using content scripts
  • How do I play a blf file in CANalzyer
  • unity / blender / FBX / semi transparent
  • DataTables Showing Duplicate Pagination And Search Controls
  • Check for value within test of TestCafe
  • NumPad keys dont work
  • Change the title of Solution Explorer in Visual Studio?
  • preserve empty cells when saving excel as xml
  • Accessing Current Tab DOM Object from a Chrome Extension
  • Speed up iteration over Numpy arrays / OpenCV cv2 image
  • Async loading script within react component
  • Problem passing parameters via Iframe in IE
  • gwt ScrollPanel in TabPanel: no vertical scrollbar
  • “Specified cast is not valid” only on release build from MS build
  • can't compile a W3C-provided XSD schema; can't resolve “id”?
  • Unescaping special character sequences in Ruby strings
  • Cannot override Java function in Kotlin
  • Main differences/features among the most known NoSQL systems
  • SSIS Flat-file source - Text was truncated or one or more characters had no match in the target code
  • How to get current tab index in Flutter
  • data.table equivalent of tidyr::complete with group_by with on and by syntax
  • Play 2 - Scala - Forms Validators and radio buttons
  • Convert pandas multiindex dataframe to nested dictionary
  • viewWillAppear not firing for UIViewController that belongs to UITabBarController until I switch tab
  • Remove divider after last item while using ngFor
  • Does Firebase Email and Password authentication have any security configuration options?
  • How to prevent d3.drag().on('end' from firing .on('click'
  • Reflection: Why are there methods like setAccessible()?
  • Multiple instances of tinyMCE on fields with same ID
  • Attribute target=“_newtab” for links
  • MySql conditional Insert with dynamic values
  • Error launching native application from web app - iOS - URL can't be shown
  • Mongodb conditional sort
  • Problems with error: “Access to the path is denied.”
  • BeautifulSoup can't find class that exists on webpage?
  • phpunit - Help needed about risky tests
  • How to decrypt a pkcs8 encrypted private key using bouncy castle?
  • Swagger: support for optional routes
  • Finding hour of daily max using Pandas in Python
  • Update SelectOneMenu if value of ohter SelectOneMenu is set (Event isn't fired)
  • Pandas, Computing total sum on each MultiIndex sublevel
  • Eclipse code formatter: how to remove its effects?
  • jQuery AutoComplete select firing after change?
  • Is defining the length of an array with a macro “excellent practice”?
  • warning message linking against a dylib which is not safe for use in application extensions
  • Android YouTube API “An error occurred while initializing YouTube player”
  • Unable to locate Spring NamespaceHandler util
  • Show Link on image at hovering in jquery
  • VSCode Open new view into file
  • How to check if a list contains only #t
  • Delete from table if the id doesn't exists in another table
  • gradle - not able to find dependencies from maven repo
  • Tabbing behavior in WebForms
  • Disable Tabs in TabLayout
  • Side effects within a typeof() expression
  • Spark streaming is not working in Standalone cluster deployed in VM
  • Adding multiple rows to DataTable
  • Lambda expressions of .NET in Java
  • Is there a way to find the event handlers of an element with Javascript?
  • Angular ui-router passing data between subviews of the same state
  • Building a war on intellij
  • restore tabs after reopening SQL Server Management Studio
  • Ribbon tab exists even after uninstalling PowerPoint Add-in
  • How I can check android device is connected to the Internet? [duplicate]
  • how to pass values from python code to variable of robot framework
  • Shinyjs: On click option in shiny dashboard
  • Python Selenium Webpage with Windows Security
  • Disable taphold default event, cross device
  • Mixing List and Dict in Python
  • How to download a PDF that is in a hyperlink using VB in Outlook 2016 [closed]
  • How to Mantain Session with AngularJS Website from Native App?
  • umount doesn't work with device in C (but it works in Terminal)
  • Unable to run Excel VSTO Add-ins
  • Move a ant dir project after the ant or subant task completes
  • Fragment Onclick Listener
  • Share dialog: “Sorry, sharing is unavailable at this time. Please try again later.”
  • Get age of friend on Facebook with Ruby via rFacebook
  • how to design tab which onselect comes in center of a tabhost
  • How to marry NioServerSocketChannelFactory and WorkManager
  • Android : Radio Buttons keep changing their state when List View Scrolled
  • How to color specific rows in a JTable
  • Check if Timer is running
  • perl - Math with duplicate entries in array
  • Google Spreadsheets Copy Value and Formats Script Issues
  • @org.omnifaces.cdi.ViewScoped invokes @PostConstruct on unload of an already destroyed view
  • How to log MDC with Spring Sleuth 2.0?
  • Python and PHP SOAP server
  • Export Sql Server 2008 database into MS Access Database
  • Inject Javascript code into a web page
  • pip installation of gmpy2
  • Inject Javascript code into a web page
  • Inject Javascript code into a web page
  • Inject Javascript code into a web page
  • Inject Javascript code into a web page
  • Inject Javascript code into a web page
  • How to create device specific layouts?
  • mat tab inside tab selected index not working
  • Switch back to parent tab using selenium webdriver
  • Apprequest of Android Facebook sdk 3.0
  • Spark sql issue with columns specified
  • How to change tabs width in material UI
  • Why WebSphere 6.1 (JDK 1.5 Compliant) compiles my JSPs as JDK 1.4?
  • CSS button not styling
  • Rails 3 Full_Calendar
  • Stop the background service after particular time in android
  • Sending in an object of type Object instead of String - Polymorphism
  • JQuery and PHP validation problem?
  • Share Application Through Facebook, Twitter, Email, and Messaging Only
  • Is there a way to remove a script from a doc (using the new doc embedded script)
  • Re-order an array's items based on several criteria
  • AngularJS Dynamic Directives inside ng-repeat
  • Identify File Type in Java
  • DocuSign API Replace template document but keep fields
  • Insert statement not working using execute(array()) of PDO Extension
  • Arc gradients in Flutter?
  • Eric5: The OK button of 'new project' dialog is disable
  • Java 11 and E(fx)clipse JavaFX plugin on Eclipse 4.9: An error has occurred - see the log file
  • android : speech recognition what are the technologies available
  • $this->a->b->c->d calling methods from a superclass in php
  • Reader monad - how does it conform to Monad interface?
  • How to convert days into months using datetime in Python3?
  • Protractor Page objects - TypeError: Object # has no method 'methodName'
  • How can I filter an array of dictionaries in 'updateSearchResultsForSearchController' to s
  • Issue with Terrain Collision using Three.js
  • JQuery Mobile Ajax Navigation in Single-Page Template
  • Swift: UIView.animate works unexpectedly
  • Is there a better way for handling SpatialPolygons that cross the antimeridian (date line)?
  • How to include associated objects using gon in Rails/jQuery
  • How to call jQuery function in HTML returned by AJAX
  • How do I add a mouse over tooltip to an Image using .DrawImage()
  • How to warp text around image in iOS?
  • Can someone explain this Java code (formatting the output using System.out.format) to me?
  • Android Library Projects on Windows and Mac
  • Jersey serializes character value to ASCII equivalent numeric string
  • JavaScript RegExp Replace