avorum
avorum

Reputation: 2293

how to add a instance of a foreign key to an instance of a model that it points to

I have a Django app wherein a user can schedule command line 'Jobs' to run on remote systems. Here's my models.py defining Job and a foreign key relationship

class Job(models.Model):
    name = models.CharField(max_length = 250, null = False, blank = False)
    user = models.CharField(max_length = 30, null = False, blank = False)
    command = models.CharField(max_length = 1000, null = False, blank = False)
    whenToRun = models.DateTimeField('Run Date', null = False, blank = False)
    output = models.CharField(max_length = 100000, null = True, blank = True)

class Host(models.Model):
    job = models.ForeignKey(Job)
    name = models.CharField(max_length = 100, null = False, blank = False)
    hasRun = models.BooleanField(default = False)

Next I have a block of code that has some POST data indicating some hosts to add to a Job (hosts represent individual host names that the user wants to be running the command specified in the Job instance that the Host instance is connected to).

hostNames = list()
for p in request.POST:
    if "Host" in p: #Host is put in the input name attribute in the template as a sentinel
        hostNames.append(request.POST[p])
selected = getCheckedJobs() #a list of the jobs to add this host to

Now that I have the names assembled and jobs to add them to, I realize that I have no idea how to take a Job instance and add a Host instance that's associated with it. Can anyone tell me how to go about this? Thanks in advance for any help.

Upvotes: 0

Views: 64

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

Are you sure you have the right relationship structure? With the foreign key on Host, each job can have many hosts but each host can only have one job. Your comment says "a list of jobs to add this host to" - that's not possible with this relationship.

If it is right - you need to get your Host instance, then assign its job attribute to be the Job instance and save the Host instance. Something like:

# assume selected_job is the job instance
try:
    host = Host.objects.get(name=hostname)
except ObjectDoesNotExist:
    # do something here to handle an unmatched hostname
    pass
host.job = selected_job
host.save()

Upvotes: 2

Related Questions