Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Quantity fields don't work using temperature units ("°C", "K", etc.) #90

Closed
SamuelJennings opened this issue Sep 14, 2023 · 1 comment

Comments

@SamuelJennings
Copy link
Contributor

Issue

Temperature units are special in pint as they "are non-multiplicative units" (see Pint docs here). The current implementation in django-pint does not handle these properly and declaring a field with temperature units and attempting to save will raise:

pint.errors.OffsetUnitCalculusError: Ambiguous operation with offset unit (degree_Celsius). See https://pint.readthedocs.io/en/stable/user/nonmult.html for guidance.

Solution

Thankfully, I think the solution is pretty simple. In quantityfields.fields, first:

class QuantityFieldMixin(object):
    ...
    def from_db_value(self, value: Any, *args, **kwargs) -> Optional[Quantity]:
        if value is None:
            return None
    #     return self.ureg.Quantity(value * getattr(self.ureg, self.base_units))
      return self.ureg.Quantity(value, getattr(self.ureg, self.base_units))

and then also,

class QuantityFormFieldMixin(object):
    ...
    def clean(self, value):
        ...
        # val = self.ureg.Quantity(val * getattr(self.ureg, units)).to(self.base_units)
        val = self.ureg.Quantity(val, getattr(self.ureg, units)).to(self.base_units)
        self.validate(val.magnitude)
        self.run_validators(val.magnitude)
        return val

As far as I'm aware, this change shouldn't affect any other fields.

@CarliJoy
Copy link
Owner

CarliJoy commented Oct 1, 2023

Fix is in 0.7.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants