Exemplo n.º 1
0
def migrate_currencies(apps, schema_editor):
    """
    Migrate from the 'old' method of handling currencies,
    to the new method which uses the django-money library.

    Previously, we created a custom Currency model,
    which was very simplistic.

    Here we will attempt to map each existing "currency" reference
    for the SupplierPriceBreak model, to a new django-money compatible currency.
    """

    logger.info("Updating currency references for SupplierPriceBreak model...")

    # A list of available currency codes
    currency_codes = CURRENCIES.keys()

    cursor = connection.cursor()

    # The 'suffix' field denotes the currency code
    response = cursor.execute(
        'SELECT id, suffix, description from common_currency;')

    results = cursor.fetchall()

    remap = {}

    for index, row in enumerate(results):
        pk, suffix, description = row

        suffix = suffix.strip().upper()

        if suffix not in currency_codes:  # pragma: no cover
            logger.warning(f"Missing suffix: '{suffix}'")

            while suffix not in currency_codes:
                # Ask the user to input a valid currency
                print(f"Could not find a valid currency matching '{suffix}'.")
                print("Please enter a valid currency code")
                suffix = str(input("> ")).strip()

        if pk not in remap.keys():
            remap[pk] = suffix

    # Now iterate through each SupplierPriceBreak and update the rows
    response = cursor.execute(
        'SELECT id, cost, currency_id, price, price_currency from part_supplierpricebreak;'
    )

    results = cursor.fetchall()

    count = 0

    for index, row in enumerate(results):
        pk, cost, currency_id, price, price_currency = row

        # Copy the 'cost' field across to the 'price' field
        response = cursor.execute(
            f'UPDATE part_supplierpricebreak set price={cost} where id={pk};')

        # Extract the updated currency code
        currency_code = remap.get(currency_id, 'USD')

        # Update the currency code
        response = cursor.execute(
            f"UPDATE part_supplierpricebreak set price_currency= '{currency_code}' where id={pk};"
        )

        count += 1

    if count > 0:
        logger.info(f"Updated {count} SupplierPriceBreak rows")
Exemplo n.º 2
0
 def get_currency_codes(self):
     return sorted(list(CURRENCIES.keys()), key=str.lower)