Issue
Just to note: I know about overwriting Model's .save() method but it won't suit me as I explained it at the end of my question.
In one of my projects, I've got more than of 30 database Models and each one of these models accept multiple CharField
to store store Persian characters; However there might be some case where users are using Arabic layouts for their keyboard where some chars are differ from Persian.
For example:
The name Ali in Arabic: علي
and in Persian: علی
Or even in numbers:
345 in Arabic: ٣٤٥
And in Persian: ۳۴۵
I need to selectively, choose a set of these fields and run a function on their value before saving them (On create or update) to map these characters so I won't end up with two different form of a single word in my database.
One way to do this is overwriting the .save()
method on the database Model. Is there any other way to do this so I don't have to change all my models?
Solution
You can create a completely custom model field however in your case it's really easier to just customize Django's CharField
:
class MyCharField(models.CharField):
def to_python(self, value):
if value is None or value == "":
return value # Prevent None values being converted to "None"
if isinstance(value, str):
return self.func_to_call(value)
return self.func_to_call(str(value))
Replace your models CharField
with MyCharField
.
And create the .func_to_call()
so it does whatever you need to map the values:
def func_to_call(self, value):
# Do whatever you want to map the values
return value
Answered By - FooBar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.