我有一个项目,我在加密文本字段中存储外键值。这样做的目的是将表格分成两组,一组具有个人身份信息,另一组没有。减少重复的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