【问题标题】:How to set up django user options for generic models如何为通用模型设置 django 用户选项
【发布时间】:2015-10-05 01:47:36
【问题描述】:

我有一个自定义用户数据的 Profile 模型:

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?

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

【问题讨论】:

    标签: python django django-models generic-foreign-key


    【解决方案1】:

    一种方法是使用单独的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()
    

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

    【讨论】:

    • 我很困惑,我已经有一个Notification 模型(如前所述)。你的意思是这可能是我提到的ProfileOptions 模型?
    • 您的问题是说您有一个“通知应用程序”——并不是说有模型——许多应用程序没有模型:-)。在任何情况下,是的,这可能是您的 ProfileOption 模型,它充当 Profile 和其他地方定义的一些任意模型之间的链接 - 假设您的所有选项都具有相同的类型(例如,布尔开/关)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2013-04-23
    • 2020-05-19
    相关资源
    最近更新 更多