Opened 5 years ago

Closed 2 months ago

#12889 closed Bug (fixed)

Using annotation unexpectedly returns DecimalFields as floats

Reported by: KyleMac Owned by: wogan
Component: Database layer (models, ORM) Version: master
Severity: Normal Keywords: annotate
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Using the following models:

class Product(models.Model):
    name = models.CharField(_('name'), max_length=64)
    price = models.DecimalField(_('price'), max_digits=5, decimal_places=2)

class Offer(models.Model):
    name = models.CharField(_('name'), max_length=64)
    start_time = models.DateTimeField(_('start time'))
    end_time = models.DateTimeField(_('end time'))
    var1 = models.DecimalField(_('var1'), max_digits=6, decimal_places=2)
    var2 = models.DecimalField(_('var2'), max_digits=6, decimal_places=2,
                               null=True, blank=True)
    contents = models.ManyToManyField(Product,
                                      verbose_name=_('contents'),
                                      related_name='offers')

Compare the following results:

now = datetime.utcnow()

# Get all running offers
offers = Offer.objects\
    .filter(start_time__lte=now, end_time__gt=now)
# Will be a Decimal as expected
print type(offers[0].var1)

# Get only running offers that have some contents
offers = Offer.objects\
    .filter(start_time__lte=now, end_time__gt=now)\
    .annotate(num_products=Count('contents'))\
    .exclude(num_products=0)
# Will be a float
print type(offers[0].var1)

Change History (9)

comment:1 Changed 5 years ago by russellm

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

comment:3 Changed 5 years ago by mk

This is a related issue: #13844 Errors when using character fields for aggregation

Last edited 2 months ago by timgraham (previous) (diff)

comment:4 Changed 4 years ago by wogan

  • Owner changed from nobody to wogan
  • Status changed from new to assigned

comment:5 Changed 4 years ago by lukeplant

  • Type set to Bug

comment:6 Changed 4 years ago by lukeplant

  • Severity set to Normal

comment:7 Changed 3 years ago by aaugustin

  • UI/UX unset

Change UI/UX from NULL to False.

comment:8 Changed 3 years ago by aaugustin

  • Easy pickings unset

Change Easy pickings from NULL to False.

comment:9 Changed 2 months ago by timgraham

  • Resolution set to fixed
  • Status changed from assigned to closed

Can't reproduce on master. Type is <class 'decimal.Decimal'> in both cases.

Note: See TracTickets for help on using tickets.
Back to Top