这对我来说是一个很难描述的问题,但我会在这里尽力而为。
我有一个用于日历事件的模型:
class Event(models.Model):
account = models.ForeignKey(Account, related_name="event_account")
location = models.ForeignKey(Location, related_name="event_location")
patient = models.ManyToManyField(Patient)
datetime_start = models.DateTimeField()
datetime_end = models.DateTimeField()
last_update = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True)
event_series = models.ForeignKey(EventSeries, related_name="event_series", null=True, blank=True)
is_original_event = models.BooleanField(default=True)
保存后,我将覆盖 save() 方法以检查是否设置了 event_series(重复事件)。如果是,那么我需要为每个重复日期迭代地创建另一个事件对象。
以下似乎可行,尽管它可能不是最好的方法:
def save(self, *args, **kwargs):
if self.pk is None:
if self.event_series is not None and self.is_original_event is True :
recurrence_rules = EventSeries.objects.get(pk=self.event_series.pk)
rr_freq = DAILY
if recurrence_rules.frequency == "DAILY":
rr_freq = DAILY
elif recurrence_rules.frequency == "WEEKLY":
rr_freq = WEEKLY
elif recurrence_rules.frequency == "MONTHLY":
rr_freq = MONTHLY
elif recurrence_rules.frequency == "YEARLY":
rr_freq = YEARLY
rlist = list(rrule(rr_freq, count=recurrence_rules.recurrences, dtstart=self.datetime_start))
for revent in rlist:
evnt = Event.objects.create(account = self.account, location = self.location, datetime_start = revent, datetime_end = revent, is_original_event = False, event_series = self.event_series)
super(Event, evnt).save(*args, **kwargs)
super(Event, self).save(*args, **kwargs)
但是,我发现的真正问题是,使用这种方法并从管理表单中保存,它会创建重复事件,但是如果我尝试获取 self.patient 这是一个 M2M 字段,我会不断收到此错误:
'Event' instance needs to have a primary key value before a many-to-many relationship can be used
我的主要问题是关于这个 m2m 错误,但如果您对重复事件的嵌套保存有任何反馈,那也很好。
非常感谢!