views:

621

answers:

2

Hi, I have a problem using the add() method below...

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

Strangely, the print self.operators.values() line displays the correct values, however, upon inspection of the record in django admin, the supervisor has not been saved as an operator.

ie.

self.operators.add(self.supervisor) # fails to commit

What manner of magic do I need here?

A: 

I've having essentially the same problem. Did you ever find a solution?

A: 

I randomly found this question so maybe is not actual, but you should save self.supervisor first:

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()
yedpodtrzitko