【问题标题】:Django model advice for chained ForeignKeys approach链式 ForeignKeys 方法的 Django 模型建议
【发布时间】:2013-06-27 10:26:33
【问题描述】:

我在 Django 1.5 中有这些模型

class Number(models.Model):
    number = models.CharField("Patient's Number", max_length=12, unique=True)

class Appointment(models.Model):
    to_number = models.ForeignKey(Number)
    message = models.CharField("Message", max_length=160)

我希望Appointment 模型保留另一个字段,允许我添加用户希望在实际预约时间之前通过电子邮件收到通知的次数(类似于我们在 Google 中添加多个弹出/电子邮件通知的方式日历)。由于我还是 Web 开发、Django 和数据库模型的新手,我很难决定如何创建和链接模型来实现这一点。我想到的一个解决方案是创建另一个模型并将其与Appointment 链接起来,如下所示:

class Notification(models.Model):
    appointment = models.ForeignKey(Appointment)
    time = models.TimeField("Time before appointment we must notify the user")

这是一个明智的方法吗?如果没有,我应该怎么做?此外,为了通过管理控制台在Number 的视图中看到AppointmentNotification,我应该声明什么内联堆栈(因为现在Number --> Apppointment --> @987654331 @,在Number 的页面下查看时,将它们链接为内联的正确方法是什么)?我知道类似 [this has been ask before] (Nested inlines in the Django admin?),但自从 2010 年被问到,我很好奇是否有人找到了新的方法,或者@carruthd 的第二个答案上述链接仍然是最好的方法。谢谢。

【问题讨论】:

    标签: django django-models django-admin


    【解决方案1】:

    如果您想为每个约会添加更多通知,请添加指向另一个模型的ManyToManyField(在本例中为Notification)。然后您就可以通过这种方式获取所有即将到来的通知: Appointment.notifications_set.filter(notify_time__gte=now()).

    class Notification(models.Model):
        notify_time = models.DateTimeField("Notification datetime", db_index=True)
    
    class Number(models.Model):
        number = models.CharField("Patient's Number", max_length=12, unique=True)
    
    class Appointment(models.Model):
        to_number = models.ForeignKey(Number)
        message = models.CharField("Message", max_length=160)
        notifications = models.ManyToManyField(Notification, through=AppointmentNotifications)
    
    class AppointmentNotifications(models.Model):
        notif = models.ForeignKey(Notification)
        appoint = models.ForeignKey(Appointment)
    

    还有一张表:AppointmentNotifications,无论如何都会由 Django 创建,但如果您自己创建它,您可以稍后添加一些列(即。notification_already_sent = models.BooleanField("User was informed"),您可能还想显示所有Notifications 作为内联加入到每个Appointment

    admin.py:

    class AppointmentNotificationInline(admin.TabularInline):
        model = AppointmentNotification
    
    class AppointmentAdmin(admin.ModelAdmin):
        inlines = [AppointmentNotificationInline]
    

    【讨论】:

    • 非常感谢@yedpodtrzitko。我肯定会尝试一下,并确认这里是否/如何工作。非常感谢您花时间帮我解释这一点。
    猜你喜欢
    • 2012-06-20
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 2011-08-20
    • 1970-01-01
    相关资源
    最近更新 更多