Reputation: 7745
I am fairly new to Django coming from Laravel background. I would like to modify a field value everytime I query it. For example, every time you query firstname@User you return the Capitalized firstname. In Laravel this is known as Accessors but apparantely Accessors have different meaning in Django. For my case, I have a key-value table called Meta
where the value
field can be of any type:
class Meta(models.Model):
key = models.CharField(max_length=30)
value = models.TextField()
model = models.ForeignKey('Model', on_delete=models.CASCADE)
and upon getting the value Meta.objects.get(key='foo')
, I would like to return ast.literal_eval(value)
to convert the string expression to the correct respective type. I did some research and only found the following:
get_foo_display(self)
but this only works for ChoiceField as far as I understood.What is the best choice to apply this function for everytime I query value
filtering by the key
Upvotes: 0
Views: 338
Reputation: 2061
a @property is a good approach, but if you will access a lot of time ast.literal_eval and the processing is costly, you can overrride the save method:
def __init__(self, *args, **kwargs):
super(Meta, self).__init__(*args, **kwargs)
self.__original_value = self.value
def save(self, **kwargs):
if self.__original_value != self.value:
self.value = ast.literal_eval(self.value)
super(Meta, self).save()
The init will pick the value before the update
Upvotes: 1
Reputation: 599630
You could use a custom field, but the easiest thing here is to use a property.
class Meta(models.Model):
value = models.TextField()
@property
def converted_value(self):
return ast.literal_eval(self.value)
Now you can access my_meta.converted_value
whenever you need that converted value.
Upvotes: 2