简体   繁体   中英

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 .

For example;

  • Saving a user with username 'Username123' and is_staff=False will create a user object in the database with value 'customer:Username123'
  • Saving a user with username 'Username123' and is_staff=True will create a user object in the database with value '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. 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). 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

I have also tried making the username field not unique, but decided that this was a bad idea as django warns against this.

Does anyone have any recommendations on how to both save and query against the prefixed value which depends on the is_staff flag?

Create a property in the model that renders the value you need based on the is_staff value:

@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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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