views:

657

answers:

3

Hello

The following does not quite work, its purpose is:

Upon save, check for the existence of 'supervisor' in the 'operators', and add it too them if not.

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)

Thanks for your expertise, would be 'expert'!

+1  A: 

You can do something like this to check if the supervisor is in the operators:

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

And you don't need to save a second time after modifying the many to many field. (Many to many relations are stored in their own table.)

Matthew Marshall
half way there... the conditional works, yet the add() method doesn't quite crack it?
Antonius Common
A: 

Ok, I've modified the to make the following. Actually, either conditional seems to do the trick. The issue now is that the add() method is not working for me.

#...

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?
Antonius Common
Are you sure it's not adding? Do you get an exception? Try printing self.operators.all()
Matthew Marshall
You may want to review the many-to-many api usage: http://www.djangoproject.com/documentation/models/many_to_many/
Matthew Marshall
A: 

i have the same issue. if you are using a django form, do your check after the form is saved, and then add the many to many there. that was the only way i could get around it.

Brandon H