Django模型 - 在保存之前有条件地将对象添加到ManyToManyField

时间:2009-03-10 23:53:20

标签: django-models

以下不太有效,其目的是:

保存后,检查“运营商”中是否存在“主管”,如果没有,也将其添加。

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 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'))

    # --- over ride methods ---- #

    def save(self, **kwargs):
        # this must be done to get a pk
        super(JobRecord, self).save(**kwargs)

        # which makes this comparison possible
        if self.supervisor not in self.operators.__dict__:
            self.operators.add(self.supervisor)

        # it seems to get this far ok, but alas, the second save attempt
        # does not seem to work!
        print self.operators.values()
        super(JobRecord, self).save(**kwargs)

感谢您的专业知识,将是'专家'!

3 个答案:

答案 0 :(得分:2)

您可以执行以下操作来检查主管是否在运营商中:

if self.operators.filter(id=self.supervisor.id).count() == 0:

修改多对多字段后,您无需再次保存。 (多对多关系存储在自己的表中。)

答案 1 :(得分:1)

好的,我已经修改过以进行以下操作。实际上,任何条件似乎都可以解决问题。现在的问题是add()方法对我不起作用。

#...

def save(self, **kwargs):
    super(JobRecord, self).save(**kwargs)

    if self.operators.filter(id=self.supervisor.id).count() == 0:
    #if self.supervisor not in self.operators.values():

        # either conditional will get to this point
        self.operators.add(self.supervisor) # <-- this line doesn't save proper?

答案 2 :(得分:0)

我有同样的问题。如果您使用的是django表单,请在保存表单后进行检查,然后在那里添加多个表单。这是我能绕过它的唯一方法。