如何将外键的实例添加到它指向的模型的实例

时间:2013-06-21 18:53:42

标签: python mysql django foreign-keys models

我有一个Django应用程序,其中用户可以安排命令行'Jobs'在远程系统上运行。这是我的models.py定义Job和外键关系

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)

接下来我有一段代码,其中包含一些POST数据,表明要添加到作业的一些主机(主机代表用户希望运行在Host实例所连接的Job实例中指定的命令的各个主机名) )。

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

现在我已经组装了名称和添加它们的作业,我意识到我不知道如何获取Job实例并添加与之关联的Host实例。任何人都可以告诉我如何去做吗?提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您确定自己拥有正确的关系结构吗?使用Host上的外键,每个作业可以有多个主机,但每个主机只能有一个作业。您的评论说“添加此主机的作业列表” - 这种关系无法实现。

如果它是正确的 - 您需要获取您的Host实例,然后将其job属性指定为Job实例并保存Host实例。类似的东西:

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