Simanas
Simanas

Reputation: 2793

Dynamically alter django model's field return value

Let's say I have a setup similar to this:

class UnitsOfMeasure(models.Model):
    name = models.CharField(max_length=40)
    precision = models.PositiveIntegerField()

class Product(models.Model):
    name = models.CharField(max_length=100)
    uom = models.ForeignKey(UnitsOfMeasure)
    qty_available = models.DecimalField(max_tigits=10, decimal_places=10)

Now lets say we have a product related to Units of measure instance with precision = 2. How can I do that qty_available would return 5.50 instead of 5.5000000000?

I know I can use property decorator, but this does not solve my problem, since I want to use qty_available as a field in forms.

Custom Field type? How can I pass and access related model instance then??

Your ideas are very appreciated!

Upvotes: 0

Views: 154

Answers (2)

Germano
Germano

Reputation: 2482

If it's just a presentation problem, you can use a simple_tag in your templates:

@register.simple_tag
def format_qty_available(product):
    return product.qty_available.quantize(Decimal(10) ** -product.uom.precision)

Upvotes: 0

Alasdair
Alasdair

Reputation: 308939

Override the __init__ method of your model field and set the max_digits based on the related unit of measure.

class ProductForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['qty_available'] = models.DecimalField(max_digits=10, decimal_places=self.instance.uom.precision)
    class Meta:
        model = Product

Upvotes: 1

Related Questions