Last active
January 26, 2021 10:21
-
-
Save rajeshr188/9cf4143fa1113166a1b5ed3a5c859483 to your computer and use it in GitHub Desktop.
Creating ArrayField of custom basefield in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from moneyed import Money | |
from psycopg2.extras import register_composite | |
from psycopg2.extensions import register_adapter, adapt, AsIs | |
MoneyValue = register_composite( | |
'money_value', | |
connection.cursor().cursor, | |
globally=True | |
).type | |
def moneyvalue_adapter(value): | |
return AsIs("(%s,%s)::money_value" % ( | |
adapt(value.amount), | |
adapt(value.currency.code))) | |
register_adapter(Money, moneyvalue_adapter) | |
class MoneyValueField(models.Field): | |
description = "wrapper for money_value composite type in postgres" | |
def from_db_value(self,value,expression,connection): | |
if value is None: | |
return value | |
return Money(value.amount,value.currency) | |
def to_python(self,value): | |
if isinstance(value,Money): | |
return value | |
if value is None: | |
return value | |
return Money(value.amount,value.currency.code) | |
def get_prep_value(self, value): | |
# in input box we enter 10 USD,20 INR,30 AUD | |
amount,currency = value.split() | |
return Money(decimal.Decimal(amount),currency) | |
def db_type(self,connection): | |
return 'money_value' | |
class Transaction(models.Model) | |
amount = MoneyValueField() | |
class Balance(models.Model) | |
bal = ArrayField(MoneyValueField(),size = 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment