這是一個很難描述的問題,但我會盡我所能。Django難以在保存方法中保存多個模型對象
我有一個模型,它是一個日曆事件:
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)
當這個被保存我重寫保存()方法來檢查,看看是否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錯誤,但如果你還對嵌套任何反饋爲經常性事件節省,這也會很好。
非常感謝!
謝謝布魯諾!我在1中看到明顯的冗餘。:)謝謝你指出。 – bevinlorenzo
另外,我可以設置另一種添加M2M的方法,但它應該放在哪裏以及如何調用它以確保它在保存後立即運行? – bevinlorenzo
有人能解決這個問題嗎?我也問過同樣的問題[這裏](http://stackoverflow.com/questions/23127679/django-model-override-save-function-not-updating-m2m-field-in-db) –