you would need to use the "on load" events to detect this and replace the value with None using set_committed_value()

from sqlalchemy.orm import set_committed_value
from sqlalchemy import event

@event.listens_for(MyClass, "load")
@event.listens_for(MyClass, "refresh")
def _replace_currency(obj, context, *arg):
    if obj._money.amount is None:
        set_committed_value(obj, '_money', None)


however, note that above, we are changing the value of "currency" from what it actually is in the database. When this object is returned, the composite here might conflict with what the "currency" attribute says.

You might be better off changing the semantics of your app either that a. your Money type represents "None" meaningfully, like Money.is_empty, something like that

b. Simon's idea below is likely a better idea, that is, don't persist "None, GBP" like that, just set it up as None on the persist side



On 05/12/2017 04:42 AM, Simon King wrote:
On Thu, May 11, 2017 at 6:18 PM,  <a...@withplum.com> wrote:
Hello,

I have a Money composite column, comprised of an `amount` (Decimal) and a
`currency` (String). Sometimes the amount needs to be NULL, but then I get
an instance of Money(None, 'GBP'). Is there any way to force the composite
to return None in this case?

I'm not sure if that's possible. As an alternative, you could do
something like this:

class YourObject(Base):
     _money = composite(Money, amount, currency)
     @property
     def money(self):
         if self._money.amount is not None:
             return self._money
         return None

Hope that helps,

Simon


--
SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to