我在使用下面的add()方法时遇到问题...
class JobRecord(models.Model):
"""JobRecord model"""
project = models.ForeignKey(Project)
date = models.DateField()
supervisor = models.ForeignKey(User, related_name='supervisor_set')
operators = models.ManyToManyField(User, related_name='operators_set', help_text='Include the supervisor as an operator here also.')
vehicles = models.ManyToManyField(Vehicle, blank=True, null=True)
def __unicode__(self):
return u"%s - %s" % (self.project.name, self.date.strftime('%b %d'))
def save(self, **kwargs):
super(JobRecord, self).save(**kwargs)
if not self.operators.filter(pk=self.supervisor.pk):
self.operators.add(self.supervisor)
print self.operators.values()
奇怪的是,print self.operators.values()
行显示正确的值,但是,在检查django admin中的记录时,主管尚未保存为运营商。
即
self.operators.add(self.supervisor) # fails to commit
我需要什么样的魔法?
答案 0 :(得分:3)
我随机发现了这个问题,所以可能不是实际的,但你应该首先保存self.supervisor:
def save(self, **kwargs):
super(JobRecord, self).save(**kwargs)
if not self.operators.filter(pk=self.supervisor.pk):
self.supervisor.save()
self.operators.add(self.supervisor)
print self.operators.values()