[英]How to override field before saving it in Django?
I have a class User in models.py
:我在models.py
中有一个 class 用户:
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 #
. userId
总是带有前缀user#
,当有#
时,我无法从数据库中查询一个用户。 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.如果我理解正确,那甚至是不可能的,所以现在我尝试修改 save 方法,以便在没有user#
前缀的情况下保存userId
。 I tried this under the User class:我在用户 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.这会正确打印 id,没有前缀,但在数据库中, userId
仍然与它一起保存。 Is there something wrong with my save -method?我的保存方法有问题吗?
You should save it to the self.userId
:您应该将其保存到self.userId
:
def save(self, *args, **kwargs):
if self.userId.startswith('user#'):
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.前缀检查是必要的,否则每次保存 object 时都会删除前五个字符,因此最终字符串将为空。
That being said, the Django ORM does not always call .save(…)
to save an object.话虽如此,Django ORM 并不总是调用.save(…)
来保存 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:如果我用 hash ( #
) 查询 object,它会返回正确的项目:
>>> 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)>]>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.