[英]How to set up django user options for generic models
我有一個用於自定義用戶數據的配置文件模型:
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False)
# more stuff...
我也有一個Notifications應用程序,該應用程序允許模型向用戶發送通知和電子郵件。
我希望用戶可以選擇打開或關閉不同的通知,但是我不想像這樣向配置文件中添加大量的布爾字段列表:
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是通知的來源是某種模型或其他應用程序,而notifyx / emailx是通知的某些特定原因。
我在想一種更可持續的方法是創建一個ProfileOptions模型,外部模型可以使用該模型來定義自己的通知設置。
這樣,當我添加一個新的應用程序/模型時,我可以將其通知源以某種方式鏈接到ProfileOptions模型,並使這些選項將其打開或關閉以魔術方式顯示在用戶的配置文件中。
這有意義嗎? 如果是這樣,有可能嗎? 如果是這樣,這是一個好主意嗎? 如果是這樣,我應該使用什么結構來連接模型,ProfileOptions和用戶的Profile?
顯然,我希望找到最后一個問題的答案,但我不想排除其他問題的答案可能為“否”的可能性。
一種方法是擁有一個單獨的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()
這種方法可以讓您處理任意數量的通知源模型(每個源模型具有任意數量的通知),而無需嘗試將所有通知信息都壓縮到用戶配置文件中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.