python - 从基本模型实例转换为 Django 中的派生代理模型?

标签 python django django-models

我想为 Django 的默认用户类定义一个代理模型,有点像这样:

class MyUser(User):

    def pretty_username(self): 
        if self.first_name:
            return self.first_name
        return self.username 

    class Meta: 
        proxy = True 

而且,我希望能够从 View 代码中调用 pretty_username(理想情况下,甚至是从模板中)。有没有一种简单的方法可以获取标准用户模型的实例并将其类型转换为 MyUser 的实例?

即使是一些__init__魔法对我来说也没问题,只要我能说:

my_user = MyUser(request.user) 

在我的 View 代码中。

最佳答案

我认为这个问题的实际答案应该是@fhahn 在另一个答案中的评论。通过更改 class 我们可以避免额外的数据库调用。这是示例代码:

如果设置,我的代理模型将表示从 username 更改为 email:

class MyUser(User):
    class Meta:
        proxy = True
        verbose_name = _('my user')
        verbose_name_plural = _('my users')

    def __str__(self):
        return "%s" % (self.email or self.username)

class Wallet(models.Model):
    owner = models.OneToOneField(MyUser, on_delete=models.PROTECT, related_name='wallet')

    def __str__(self):
        return "%s" % self.owner

shell 中的简短测试:

>>> from django.contrib.auth.models import User
>>> from my_apps.models import MyUser
>>> user = User.objects.get(pk=4)
>>> user
<User: AbKec6rumI9H9UmAC3Bh2kXUHzj4>
>>> user.email
'john@example.com'
>>> user.wallet
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'User' object has no attribute 'wallet'
>>> user.__class__ = MyUser
>>> user
<MyUser: john@example.com>
>>> user.wallet
<Wallet: john@example.com>

关于python - 从基本模型实例转换为 Django 中的派生代理模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7919592/

相关文章:

python - 在 python 3 中使用全局变量

Django 数据库错误 : relation "django_site"

javascript - javascript 中的 Django 列表项

python - 将 'auto_now' DateTimeField 添加到现有的 Django 模型

python - 属性错误: module 'pygmo' has no attribute 'spea2'

python - 相关对象不存在 : User has no userprofile

python - 文件 "<string>"第 1 行,在 <module> 中 NameError : name ' ' is not defined in ATOM

python - Django AUTHENTICATION_BACKENDS 导入错误

python - 对 django 中列表列表的元素进行排名和计数

python - Django REST Framework 序列化 ForeignKey 和 ManyToManyFields