简体   繁体   English

Django字段-如何基于另一个字段的值为字段的db值添加前缀?

[英]Django Fields - How to prefix a field's db value based on another field's value?

I am trying to namespace the username field of the user object depending on the value of is_staff . 我正在尝试根据is_staff的值对用户对象的用户名字段命名空间。

For example; 例如;

  • Saving a user with username 'Username123' and is_staff=False will create a user object in the database with value 'customer:Username123' 用用户名“ Username123”和is_staff = False保存用户将在数据库中创建一个值“ customer:Username123”的用户对象
  • Saving a user with username 'Username123' and is_staff=True will create a user object in the database with value 'staff:Username123' 用用户名“ Username123”和is_staff = True保存用户将在数据库中创建一个用户对象,其值为“ staff:Username123”

The reason for doing this is that users can be authorised through active directory or Oauth2 on a Web Application I am working on. 这样做的原因是可以通过我正在使用的Web应用程序上的活动目录或Oauth2对用户进行授权。 As the username needs to be unique I am trying to use name-spacing to avoid conflicts from two users with the space username, but authorised from different sources. 由于用户名必须唯一,因此我尝试使用名称空间来避免两个用户与空间用户名发生冲突,但要获得不同来源的授权。

I've looked into using the from_db_value and get_prep_value methods, but these don't provide the user object (thus, no way to determine the is_staff value). 我已经研究过使用from_db_valueget_prep_value方法,但是这些方法不提供用户对象(因此,无法确定is_staff值)。 The pre_save provides access to the user model, but does not help when querying eg .filter(username='Username123', is_staff=True) to filter Users with username staff:Username123 pre_save提供对用户模型的访问,但是在查询例如.filter(username='Username123', is_staff=True)来过滤具有用户名staff:Username123 .filter(username='Username123', is_staff=True)

I have also tried making the username field not unique, but decided that this was a bad idea as django warns against this. 我也尝试过使用户名字段不是唯一的,但由于django警告对此,因此认为这不是一个好主意。

Does anyone have any recommendations on how to both save and query against the prefixed value which depends on the is_staff flag? 是否有人对如何根据is_staff标志保存和查询前缀值有任何建议?

Create a property in the model that renders the value you need based on the is_staff value: 在模型中创建一个属性,该属性根据is_staff值呈现所需的值:

@property
def namespace(self):
   return '%s:%s' % ('staff' if is self.is_staff else 'customer', self.username)

I would avoid saving the namespace in the database because you have to maintain the value if something changes. 我会避免将namespace保存在数据库中,因为如果发生某些更改,则必须保留该值。 eg the user is not any more staff or other changes in the creation of the namespace. 例如,用户不再需要任何人员或名称空间创建中的其他更改。

In your code just refer to user.namespace 在您的代码中仅引用user.namespace

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM