DanielleC
DanielleC

Reputation: 127

Django-How to create a field based on another field in the same model

I am trying to create a field for each Person that stores the pinyin (translate Chinese characters into letters) of that person's name, using function pinyin()(which is working and tested). But I can't seem to create the field name_pinyin based on the name field in the same model. Is this the correct way to approaching this problem? Thanks in advance

from django.db import models
from xpinyin import Pinyin

class Person(models.Model):
    address = models.CharField(max_length500)
    name = models.CharField(max_length=200)
    name_pinyin = models.CharField(pinyin(name),max_length = 200)

    def pinyin(self):
        p=Pinyin()
        return p.get_Pinyin()(str(self),'') 
    #This is a function that returns pinyin of chinese characters

Upvotes: 0

Views: 459

Answers (1)

Newtt
Newtt

Reputation: 6200

You could use the model save method like this:

class Person(models.Model):
    address = models.CharField(max_length500)
    name = models.CharField(max_length=200)
    name_pinyin = models.CharField(pinyin(name),max_length = 200)

    def save(self, *args, **kwargs):
        self.name_pinyin = Pinyin(self.name)
        super(Person, self).save()

Upvotes: 2

Related Questions