Django User 模型,添加功能

发布于 2024-09-03 08:27:35 字数 373 浏览 7 评论 0 原文

我想向 Django 的默认用户模型添加一个新函数,用于检索模型类型的相关列表。

这样的Foo模型:

class Foo(models.Model):
    owner = models.ForeignKey(User, related_name="owner")
    likes = models.ForeignKey(User, related_name="likes")

........

    #at some view
    user = request.user
    foos= user.get_related_foo_models()

这如何实现?

I want to add a new function to the default User model of Django for retrieveing a related list of Model type.

Such Foo model:

class Foo(models.Model):
    owner = models.ForeignKey(User, related_name="owner")
    likes = models.ForeignKey(User, related_name="likes")

........

    #at some view
    user = request.user
    foos= user.get_related_foo_models()

How can this be achieved?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

白况 2024-09-10 08:27:36

正如文档中所述,替换用户模型并不罕见: https://docs.djangoproject.com/es/1.9/topics/auth/customizing/#substituting-a-custom-user-model,因此,考虑到这一点,最好使用以下代码获取用户模型类:

from django.contrib.auth import get_user_model
UserModel = get_user_model()

之后,您可以使用此 UserModel 按照 @Lakshman Prasad 的建议添加功能:UserModel.add_to_class('get_lated_foo_models', get_lated_foo_models)< /代码>。


为了让代码只执行一次,我更喜欢使用 Django 应用程序配置类 (https: //docs.djangoproject.com/es/1.9/ref/applications/),所以一个完整的工作示例将是:

# myapp/__init__.py
default_app_config = 'myapp.apps.MyAppConfig'

# myapp/apps.py
from django.apps import AppConfig
from django.contrib.auth import get_user_model


class MyAppConfig(AppConfig):
    name = 'myapp'
    verbose_name = 'MyApp'

    def ready(self):
        # Add some functions to user model:
        def custom_function(self):
            # Do whatsoever
            pass

        UserModel = get_user_model()
        UserModel.add_to_class('custom_function', custom_function)

It's not unusual to substitute user model as it is stated in the docs: https://docs.djangoproject.com/es/1.9/topics/auth/customizing/#substituting-a-custom-user-model, so, having this into account, it is better to get the user model class with the following code:

from django.contrib.auth import get_user_model
UserModel = get_user_model()

Afterwards, you can use this UserModel to add functionality as @Lakshman Prasad suggests: UserModel.add_to_class('get_related_foo_models', get_related_foo_models).


In order to get the code executed only once I prefer to use Django application config classes (https://docs.djangoproject.com/es/1.9/ref/applications/), so a full working example will be:

# myapp/__init__.py
default_app_config = 'myapp.apps.MyAppConfig'

# myapp/apps.py
from django.apps import AppConfig
from django.contrib.auth import get_user_model


class MyAppConfig(AppConfig):
    name = 'myapp'
    verbose_name = 'MyApp'

    def ready(self):
        # Add some functions to user model:
        def custom_function(self):
            # Do whatsoever
            pass

        UserModel = get_user_model()
        UserModel.add_to_class('custom_function', custom_function)
缱倦旧时光 2024-09-10 08:27:36

您可以使用代理模型向用户模型添加方法,而无需更改它的类。

from django.contrib.auth import models

class UserProxy(models.User):
    class Meta:
        proxy = True
    
    def get_related_foo_models(self):
        pass

获取视图中代理模型的实例 - models.UserProxy.objects.get(pk=request.user.pk)

要立即从请求中获取代理模型的实例,您需要创建如本问题所述的自定义 ModelBackend - Django - 用户代理来自请求的模型

来源 https://docs.djangoproject.com/en/ 4.1/topics/db/models/#proxy-models

You can use a proxy model to add methods to the User model without changing it class.

from django.contrib.auth import models

class UserProxy(models.User):
    class Meta:
        proxy = True
    
    def get_related_foo_models(self):
        pass

Get an instance of the proxy model in view - models.UserProxy.objects.get(pk=request.user.pk)

To get an instance of the proxy model immediately from the request, you need to create a custom ModelBackend as described in this question - Django - User proxy model from request.

Source https://docs.djangoproject.com/en/4.1/topics/db/models/#proxy-models

無心 2024-09-10 08:27:35

您可以向 User 添加一个方法

from django.contrib import auth
auth.models.User.add_to_class('get_related_foo_models', get_related_foo_models)

,确保您在 models.py 或其他在 django 启动时导入的文件中拥有此代码。

You can add a method to the User

from django.contrib import auth
auth.models.User.add_to_class('get_related_foo_models', get_related_foo_models)

Make sure, you have this code within the models.py or some other file which gets imported in the startup of django.

小耗子 2024-09-10 08:27:35

这是@Lakshman Prasad 答案的更新。但完整的示例是:

在任何 apps:: 中创建一个文件 monkey_patching.py

#app/monkey_patching.py
from django.contrib.auth.models import User 

def get_user_name(self):
    if self.first_name or self.last_name:
        return self.first_name + " " + self.last_name
    return self.username

User.add_to_class("get_user_name",get_user_name)

并将其导入到应用程序的 __init__.py 文件中。 IE::

#app/__init__.py
import monkey_patching

This is an update of @Lakshman Prasad's answer. But a full example:

create a file monkey_patching.py in any of your apps::

#app/monkey_patching.py
from django.contrib.auth.models import User 

def get_user_name(self):
    if self.first_name or self.last_name:
        return self.first_name + " " + self.last_name
    return self.username

User.add_to_class("get_user_name",get_user_name)

and import it in app's __init__.py file. ie::

#app/__init__.py
import monkey_patching
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文