Django User 模型,添加功能
我想向 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()
这如何实现?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如文档中所述,替换用户模型并不罕见: https://docs.djangoproject.com/es/1.9/topics/auth/customizing/#substituting-a-custom-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/),所以一个完整的工作示例将是:
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:
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:
您可以使用代理模型向用户模型添加方法,而无需更改它的类。
获取视图中代理模型的实例 -
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.
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
您可以向
User
添加一个方法,确保您在 models.py 或其他在 django 启动时导入的文件中拥有此代码。
You can add a method to the
User
Make sure, you have this code within the models.py or some other file which gets imported in the startup of django.
这是@Lakshman Prasad 答案的更新。但完整的示例是:
在任何
apps
:: 中创建一个文件monkey_patching.py
,并将其导入到应用程序的
__init__.py
文件中。 IE::This is an update of @Lakshman Prasad's answer. But a full example:
create a file
monkey_patching.py
in any of yourapps
::and import it in app's
__init__.py
file. ie::