2013-06-27 24 views
0

我有Django的这些模型1.5的链接ForeignKeys的Django模型的意见接近

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 - >Notification,那么将这些堆栈链接起来的正确方法是什么在Number的页面下查看时是内联的)?我知道类似于[这已经被问到](Nested inlines in the Django admin?),但是因为它在2010年被问到了,所以我很好奇,如果有人找到了一种新的方法来做到这一点,或者如果第二个回答是@carruthd在前面提到的链接仍然是最好的方式去做。谢谢。

回答

0

如果您希望为每个约会提供更多通知,请添加指向另一个模型的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] 
+0

谢谢你这么多@yedpodtrzitko我肯定会尝试了这一点,并会确认,如果/这里的东西是如何工作真的很感激塔基。你的时间来帮助我解释这一点。 – user1330974