Python django.db.models.DecimalField() Examples

The following are 30 code examples of django.db.models.DecimalField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models , or try the search function .
Example #1
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 7 votes vote down vote up
def display_for_field(value, field):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon
    from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example #2
Source File: util.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.rel, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #3
Source File: transaction.py    From byro with Apache License 2.0 6 votes vote down vote up
def with_balances(self):
        qs = self.annotate(
            balances_debit=models.Sum(
                models.Case(
                    models.When(
                        ~models.Q(bookings__debit_account=None), then="bookings__amount"
                    ),
                    default=0,
                    output_field=models.DecimalField(max_digits=8, decimal_places=2),
                )
            ),
            balances_credit=models.Sum(
                models.Case(
                    models.When(
                        ~models.Q(bookings__credit_account=None),
                        then="bookings__amount",
                    ),
                    default=0,
                    output_field=models.DecimalField(max_digits=8, decimal_places=2),
                )
            ),
        )
        return qs 
Example #4
Source File: util.py    From online with GNU Affero General Public License v3.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #5
Source File: transaction.py    From byro with Apache License 2.0 6 votes vote down vote up
def with_transaction_balances(self):
        qs = self.annotate(
            transaction_balances_debit=models.Sum(
                models.Case(
                    models.When(
                        ~models.Q(transaction__bookings__debit_account=None),
                        then="transaction__bookings__amount",
                    ),
                    default=0,
                    output_field=models.DecimalField(max_digits=8, decimal_places=2),
                )
            ),
            transaction_balances_credit=models.Sum(
                models.Case(
                    models.When(
                        ~models.Q(transaction__bookings__credit_account=None),
                        then="transaction__bookings__amount",
                    ),
                    default=0,
                    output_field=models.DecimalField(max_digits=8, decimal_places=2),
                )
            ),
        )
        return qs 
Example #6
Source File: util.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #7
Source File: util.py    From devops with MIT License 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example #8
Source File: test_ordinary_fields.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_required_attributes(self):
        class Model(models.Model):
            field = models.DecimalField()

        field = Model._meta.get_field('field')
        self.assertEqual(field.check(), [
            Error(
                "DecimalFields must define a 'decimal_places' attribute.",
                obj=field,
                id='fields.E130',
            ),
            Error(
                "DecimalFields must define a 'max_digits' attribute.",
                obj=field,
                id='fields.E132',
            ),
        ]) 
Example #9
Source File: test_ordinary_fields.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_negative_max_digits_and_decimal_places(self):
        class Model(models.Model):
            field = models.DecimalField(max_digits=-1, decimal_places=-1)

        field = Model._meta.get_field('field')
        self.assertEqual(field.check(), [
            Error(
                "'decimal_places' must be a non-negative integer.",
                obj=field,
                id='fields.E131',
            ),
            Error(
                "'max_digits' must be a positive integer.",
                obj=field,
                id='fields.E133',
            ),
        ]) 
Example #10
Source File: utils.py    From bioforum with MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, (models.BooleanField, models.NullBooleanField)):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example #11
Source File: test_ordinary_fields.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bad_values_of_max_digits_and_decimal_places(self):
        class Model(models.Model):
            field = models.DecimalField(max_digits="bad", decimal_places="bad")

        field = Model._meta.get_field('field')
        self.assertEqual(field.check(), [
            Error(
                "'decimal_places' must be a non-negative integer.",
                obj=field,
                id='fields.E131',
            ),
            Error(
                "'max_digits' must be a positive integer.",
                obj=field,
                id='fields.E133',
            ),
        ]) 
Example #12
Source File: utils.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # BooleanField needs special-case null-handling, so it comes before the
    # general null test.
    elif isinstance(field, models.BooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example #13
Source File: registration.py    From byro with Apache License 2.0 6 votes vote down vote up
def build_default_field(self, field, model):
        choices = getattr(field, "choices", None)
        if choices:
            return forms.ChoiceField(
                required=False,
                label=_("Default value"),
                choices=[(None, "-----------")] + list(choices),
            )
        if not (model is Member and field.name == "number"):
            if isinstance(field, models.CharField):
                return forms.CharField(required=False, label=_("Default value"))
            elif isinstance(field, models.DecimalField):
                return forms.DecimalField(
                    required=False,
                    label=_("Default value"),
                    max_digits=field.max_digits,
                    decimal_places=field.decimal_places,
                )
            elif isinstance(field, models.DateField):
                return forms.CharField(required=False, label=_("Other/fixed date")) 
Example #14
Source File: mapping.py    From django-seeker with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def document_field(field):
    """
    The default ``field_factory`` method for converting Django field instances to ``elasticsearch_dsl.Field`` instances.
    Auto-created fields (primary keys, for example) and one-to-many fields (reverse FK relationships) are skipped.
    """
    if field.auto_created or field.one_to_many:
        return None
    if field.many_to_many:
        return RawMultiString
    defaults = {
        models.DateField: dsl.Date(),
        models.DateTimeField: dsl.Date(),
        models.IntegerField: dsl.Long(),
        models.PositiveIntegerField: dsl.Long(),
        models.BooleanField: dsl.Boolean(),
        models.NullBooleanField: dsl.Boolean(),
        models.SlugField: dsl.String(index='not_analyzed'),
        models.DecimalField: dsl.Double(),
        models.FloatField: dsl.Float(),
    }
    return defaults.get(field.__class__, RawString) 
Example #15
Source File: utils.py    From python2017 with MIT License 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example #16
Source File: utils.py    From python with Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if getattr(field, 'flatchoices', None):
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return display_for_value(value, empty_value_display) 
Example #17
Source File: util.py    From Mxonline3 with Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if field.flatchoices:
        return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(field, models.DateTimeField):
        return formats.localize(tz_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, models.FloatField):
        return formats.number_format(value)
    elif isinstance(field.remote_field, models.ManyToManyRel):
        return ', '.join([smart_text(obj) for obj in value.all()])
    else:
        return smart_text(value) 
Example #18
Source File: utils.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def display_for_field(value, field, empty_value_display):
    from django.contrib.admin.templatetags.admin_list import _boolean_icon

    if field.flatchoices:
        return dict(field.flatchoices).get(value, empty_value_display)
    # NullBooleanField needs special-case null-handling, so it comes
    # before the general null test.
    elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
        return _boolean_icon(value)
    elif value is None:
        return empty_value_display
    elif isinstance(field, models.DateTimeField):
        return formats.localize(timezone.template_localtime(value))
    elif isinstance(field, (models.DateField, models.TimeField)):
        return formats.localize(value)
    elif isinstance(field, models.DecimalField):
        return formats.number_format(value, field.decimal_places)
    elif isinstance(field, (models.IntegerField, models.FloatField)):
        return formats.number_format(value)
    elif isinstance(field, models.FileField) and value:
        return format_html('<a href="{}">{}</a>', value.url, value)
    else:
        return smart_text(value) 
Example #19
Source File: test_decimalfield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_default(self):
        f = models.DecimalField(default=Decimal('0.00'))
        self.assertEqual(f.get_default(), Decimal('0.00')) 
Example #20
Source File: models.py    From djangoecommerce with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def total(self):
        aggregate_queryset = self.items.aggregate(
            total=models.Sum(
                models.F('price') * models.F('quantity'),
                output_field=models.DecimalField()
            )
        )
        return aggregate_queryset['total'] 
Example #21
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_number_formats_with_thousand_separator_display_for_field(self):
        display_value = display_for_field(12345.6789, models.FloatField(), self.empty_value)
        self.assertEqual(display_value, '12,345.6789')

        display_value = display_for_field(Decimal('12345.6789'), models.DecimalField(), self.empty_value)
        self.assertEqual(display_value, '12,345.6789')

        display_value = display_for_field(12345, models.IntegerField(), self.empty_value)
        self.assertEqual(display_value, '12,345') 
Example #22
Source File: test_decimalfield.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_prep_value(self):
        f = models.DecimalField(max_digits=5, decimal_places=1)
        self.assertIsNone(f.get_prep_value(None))
        self.assertEqual(f.get_prep_value('2.4'), Decimal('2.4')) 
Example #23
Source File: services.py    From django-htk with MIT License 5 votes vote down vote up
def values_equal(self, x, y):
        if isinstance(self.field_definition, models.DecimalField):
            if x is None or y is None:
                return x == y
            try:
                return self.field_definition.format_number(x) == self.field_definition.format_number(y)
            except:
                rollbar.report_exc_info(
                    extra_data={
                        'message' : 'Failed to compare values for mp {}.{}, fallback to =='.format(self.cls, self.name),
                        'x': x,
                        'y': y
                    }
                )
        return x == y 
Example #24
Source File: models.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean(self):
        """
        discount_value can hold two types of things conceptually: percentages
        and fixed amounts. We want to add extra validation here on top of the
        normal field validation DecimalField gives us.
        """
        super(EnterpriseContractMetadata, self).clean()

        if self.discount_value is not None:
            if self.discount_type == self.FIXED:
                self._validate_fixed_value()
            else:
                self._validate_percentage_value() 
Example #25
Source File: filters.py    From devops with MIT License 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example #26
Source File: filters.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example #27
Source File: functions.py    From python2017 with MIT License 5 votes vote down vote up
def __init__(self, expression, **extra):
        output_field = extra.pop('output_field', DecimalField())
        super(IntervalToSeconds, self).__init__(expression, output_field=output_field, **extra) 
Example #28
Source File: changedobject.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, model_class=None, **kwargs):
        super().__init__(*args, **kwargs)
        self._set_object = None
        self._m2m_added_cache = {name: set(values) for name, values in self.m2m_added.items()}
        self._m2m_removed_cache = {name: set(values) for name, values in self.m2m_removed.items()}
        if model_class is not None:
            self.model_class = model_class
        for field in self.model_class._meta.get_fields():
            if field.name in self.updated_fields and isinstance(field, DecimalField):
                self.updated_fields[field.name] = Decimal(self.updated_fields[field.name]) 
Example #29
Source File: filters.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def test(cls, field, request, params, model, admin_view, field_path):
        return isinstance(field, (models.DecimalField, models.FloatField, models.IntegerField)) 
Example #30
Source File: functions.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, expression, **extra):
        output_field = extra.pop('output_field', DecimalField())
        super(IntervalToSeconds, self).__init__(expression, output_field=output_field, **extra)