将自定义用户模型重构为用户 UserProfile:我应该创建自定义 UserManager 还是添加 user.get_profile() 数十次?

发布于 2024-08-27 07:58:11 字数 577 浏览 2 评论 0原文

我一直在重构一个应用程序,该应用程序通过创建 UserProfile 并使用 AUTH_PROFILE_MODULE 定义它,从 django.contrib.auth.models 自定义了标准用户模型。

问题是整个项目都使用 UserProfile 中的属性来确定用户看到的内容。

我一直在创建测试并反复放入此类语句:

user = User.objects.get(pk=1)
user_profile = user.get_profile()

if user_profile.karma > 10:
    do_some_stuff()

这很乏味,我现在想知道我是否违反了 DRY 原则。

创建一个自定义 UserManager 来在用户被请求时自动加载 UserProfile 数据是否更有意义?

我什至可以迭代 UserProfile 属性并将它们附加到 User 模型中。这将使我不必更新对乱七八糟的代码的自定义模型属性的所有引用。

当然,我必须逆向处理才能允许正确更新 User 和 UserProfile 模型。

哪种方法更像 Django 风格?

I have been refactoring an app that had customized the standard User model from django.contrib.auth.models by creating a UserProfile and defining it with AUTH_PROFILE_MODULE.

The problem is the attributes in UserProfile are used throughout the project to determine what the User sees.

I had been creating tests and putting in this type of statement repeatedly:

user = User.objects.get(pk=1)
user_profile = user.get_profile()

if user_profile.karma > 10:
    do_some_stuff()

This is tedious and I'm now wondering if I'm violating the DRY principle.

Would it make more sense to create a custom UserManager that automatically loads the UserProfile data when the user is requested.

I could even iterate over the UserProfile attributes and append them to the User model. This would save me having to update all the references to the custom model attributes that litter the code.

Of course, I'd have to reverse to process for to allow the User and UserProfile models to be updated correctly.

Which approach is more Django-esque?

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

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

发布评论

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

评论(1

长发绾君心 2024-09-03 07:58:11

就我个人而言,我不关心 get_profile() 帮助程序。我只是在 UserProfile 中使用与 User 的一对一字段并设置 lated_name='projname_profile'

然后你可以使用 ORM 魔法来获取单个请求中的所有内容(需要注意的是,我认为 select_lated 在 Django 1.2 中仅选择相反的 1-1,但也许它被向后移植了......):

user = User.objects.select_related().get(pk=1)
profile = user.projname_profile   # or just call it inline

Personally, I don't bother with the get_profile() helper. I just use a one-to-one field to User in my UserProfile and set related_name='projname_profile'.

Then you can use the ORM magic to get everything in a single request (with the caveat that I think select_related only selects the reverse 1-1 in Django 1.2 onwards, but perhaps it was backported...):

user = User.objects.select_related().get(pk=1)
profile = user.projname_profile   # or just call it inline
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文