coddingtonbear / django-measurement

Easily store, retrieve, and convert measurements of weight, volume, distance, area and more.
MIT License
145 stars 33 forks source link

Default value set to 0 returns an int instead of measurement instance #81

Closed Pacu2 closed 6 years ago

Pacu2 commented 6 years ago

Given that I have a field:

from django_measurement.models import MeasurementField
from measurement.measures import Mass

class Product(models.Model):
    weight = MeasurementField(measurement=Mass, default=0)

I'd expect the default value to be set to Mass(any_unit=0) instead of 0 as an int.

In [5]: Product.objects.create().weight
Out[5]: 0
codingjoe commented 6 years ago

@Pacu2 I am not sure if I follow. You set 0 as the default value but don't expect it to be 0. How about you do set the default to Mass(any_unit=0)? This works, or does it not?

Pacu2 commented 6 years ago

If I assign an int to the live instance and save it, it's returned as a Mass instance.

In [1]: prod = Product.objects.first()
In [2]: prod.weight = 1
In [3]: prod.save()
In [4]: prod.refresh_from_db()
In [5]: prod.weight
Out[5]: Mass(kg=0.001)

If I'll assign an int as a default model attribute, it will return it as an int instead of a Mass instance.

Setting the default to Mass(any_unit=0) works, but I think that's an inconsistency with the behavior of MeasurementField

codingjoe commented 6 years ago

Hi yes, this is correct, this does work, but line 2 will throw a warning telling not to do so ;) https://github.com/coddingtonbear/django-measurement/blob/725f47fa524ec493a38b454a552f576e7e04f6e8/django_measurement/models.py#L98-L106

It's a bit like naive datetime when you have TZ enabled. It does some guess work for you, but it's really discouraged. It is actually only still allowed for backwards compatibility.