You are not logged in.

Change Language:

Profile for jgreen

Name jgreen
Email Address joshua.w.green@gmail.com
AvatarUsers avatar
Posts1
  • Setting a model attribute whenever another model attribute is set
    Board » Django » Models
    Hello,

    I'm new to both django and python so please excuse me if the answer to this question is obvious.

    I have the following model:

    class object_value(models.Model):
        name = models.CharField(max_length='50')
        cost = models.CharField(max_length='20')
        converted_cost = models.PositiveIntegerField(editable=False)
    


    cost is a string in a particular format and converted_cost is a numerical value that can be calculated by parsing the cost. There are many cost strings that equate to the same converted cost.

    I want to store both values in the model so that I can filter by either one. However, one value is derived from the other. Whenever cost is set, I would like converted_cost to be calculated and set appropriately. Ideally, I would like converted_cost to be read only, but that's not essential.

    I know python has the notion of object properties that can do this. However I don't know how/if it's possible to combine that with a Model object. The model needs to set converted_cost to a models.PositiveIntegerField so I don't see how I could make it a property.



    Does anyone know of a way I can put this logic inside my model?
    Thanks in advance


Powered by Sphene Community Tools