如何为通用模型设置Django用户选项

2024-10-03 19:19:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个自定义用户数据的配置文件模型:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False)
    # more stuff...

我也有一个通知应用程序,允许模型发送通知和电子邮件给用户。你知道吗

我希望用户可以选择打开或关闭不同的通知,但我不希望像这样向配置文件中添加大量布尔字段列表:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False)
    send_model1_notice1 = models.BooleanField()
    send_model1_email1 = models.BooleanField()
    send_model1_notice2 = models.BooleanField()
    send_model1_email2 = models.BooleanField()
    send_model2_notice1 = models.BooleanField()
    send_model2_email1 = models.BooleanField()
    send_model3_notice1 = models.BooleanField()
    send_model3_email1 = models.BooleanField()
    # etc...

其中modelx是某个模型或某个其他应用程序,它是通知的来源,noticex/emailx是通知的特定原因。你知道吗

我在想一个更可持续的方法是创建一个ProfileOptions模型,外部模型可以用它来定义自己的通知设置。你知道吗

这样,当我添加一个新的应用程序/模型时,我可以以某种方式将其通知源链接到ProfileOptions模型,并让这些打开或关闭它们的选项神奇地出现在用户的配置文件中。你知道吗

这有道理吗?如果是,有可能吗?如果是这样,这是个好主意吗?如果是这样,我应该使用什么结构来连接模型、ProfileOptions和用户的Profile?你知道吗

显然,我希望最后一个问题能得到答案,但我不想排除其他问题答案可能是“不”的可能性。你知道吗


Tags: 用户模型send应用程序modelmodels配置文件profile
1条回答
网友
1楼 · 发布于 2024-10-03 19:19:38

一种方法是建立一个单独的Notification模型,将两者联系起来:

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Notification(models.Model):
    # Foreign key to user profile
    user = models.ForeignKey(Profile)

    # Generic foreign key to whatever model you want.
    src_model_content_type = models.ForeignKey(ContentType)
    src_model_object_id = models.PositiveIntegerField()
    src_model = GenericForeignKey('src_model_content_type', 'src_model_object_id')

    # Notification on or off. Alternatively, only store active notifications.
    active = models.BooleanField()

这种方法可以让您处理任意数量的通知源模型(每个模型都有任意数量的通知),而无需将所有通知信息压缩到您的用户配置文件中。你知道吗

相关问题 更多 >