简体   繁体   中英

How to override field before saving it in Django?

I have a class User in models.py :

class User(models.Model):
    userId = models.CharField(primary_key=True, blank=False, max_length=100)

The userId always comes with a prefix user# and I have not been able to query one user from the db when there is # . If I understood correctly, that is not even possible so now I've tried to modify the save method so that the userId would be saved without the user# prefix. I tried this under the User class:

def save(self, *args, **kwargs):
    userId = self.userId[5:]
    print("USER_ID: ", userId)
    super(User, self).save(*args, **kwargs)

That prints the id correctly, without the prefix but in the database the userId is still saved with it. Is there something wrong with my save -method?

You should save it to the self.userId :

def save(self, *args, **kwargs):
    if self.userId:
         = self.userId[5:]
    super().save(*args, **kwargs)

The prefix check is necessary, since otherwise you will remove the first five characters each time you save the object, and as a result, eventually the string will be empty.

That being said, the Django ORM does not always call .save(…) to save an object. Indeed, a lot of operations to create/update items in bulk will not call the user.

If I query the object with a hash ( # ), it returns the correct item:

>>> User.objects.create(userId='foo#bar')
<User: User object (1)>
NameError: name 'Unit' is not defined
>>> User.objects.filter(userId='foo#bar')
<QuerySet [<User: User object (1)>]>

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