我有一個項目,我在加密文本字段中存儲外鍵值。這樣做的目的是將表格分成兩組,一組具有個人身份信息,另一組沒有。減少重複的Django模型代碼
class User(AbstractBaseUser):
# ... fields
encrypted_identification_id = models.TextField(null=True)
encrypted_identification_key = models.TextField(null=True)
def get_identification(self, private_key):
if not self.encrypted_identification_key:
return None
identification_id = decrypt(private_key, self.encrypted_identification_id, self.encrypted_identification_key)
return Identification.objects.get(pk=identification_id)
def set_identification(self, identification):
encrypted = encrypt(str(identification.pk))
self.encrypted_identification_id = encrypted['encrypted_string']
self.encrypted_identification_key = encrypted['aes_key']
self.save()
class Identification(models.Model):
# ... fields
encrypted_user_id = models.TextField(null=True)
encrypted_user_key = models.TextField(null=True)
def get_user(self, private_key):
if not self.encrypted_user_key:
return None
user_id = decrypt(private_key, self.encrypted_user_id, self.encrypted_user_key)
return User.objects.get(pk=user_id)
def set_user(self, user):
encrypted = encrypt(str(user.pk))
self.encrypted_user_id = encrypted['encrypted_string']
self.encrypted_user_key = encrypted['aes_key']
self.save()
的代碼字段和方法的不同之處在於他們有和使用不同的名稱相同的:每個帶有該功能模型2場和2種方法實現它。我有很多像這樣的模型,都複製並粘貼了看起來像這樣的代碼。減少這種重複的最有效方法是什麼?
此封裝的方法,而不是字段,以便有什麼意義呢?這些字段仍然必須以聲明方式定義。 – hekevintran 2014-12-27 19:34:04