在django中插入许多属于同一模型的外键

qgelzfjb  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(179)

我是django的新手,正在建立一个工作门户。当招聘人员发布一个实习岗位时,它可以有很多技能。这些技能我用外键存储在不同的表中。然而,我不知道如何正确地插入。获取错误
请帮忙
这是我的密码
型号.py

class Internship(models.Model):
    MODE_CHOICES = (
    ('Office', 'Office'),
    ('Work From Home', 'Work From Home'),
    ('Blended', 'Blended'),
)
     recruiter = models.ForeignKey(Recruiter, on_delete=models.SET_NULL, null=True)
     internship_title = models.CharField(max_length=100)
     internship_mode = models.CharField(max_length=20, choices=MODE_CHOICES)
     industry_type = models.CharField(max_length=200)
     internship_desc = RichTextField()
     start_date = models.DateField()
     end_date = models.DateField()
     internship_deadline = models.DateField()
     posted_date = models.DateField()

     def __str__(self):
          return self.internship_title

class InternshipSkill(models.Model):
     internship = models.ForeignKey(Internship, on_delete=models.CASCADE)
     skill = models.CharField(max_length=50)

     def __str__(self):
          return self.internship+" "+self.skill

视图.py

def post_internship(request):
    if request.method == 'POST':
        start_date = request.POST['start_date']
        end_date = request.POST['end_date']
        internship_title = request.POST['internship_title']
        internship_mode = request.POST['internship_mode']
        industry_type = request.POST['industry_type']
        internship_deadline = request.POST['app_deadline_date']
        skills = request.POST.getlist('internship_skills[]') #gets a list
        emp_steps = request.POST.getlist('employement_steps[]')
        internship_desc = request.POST['internship_desc']

        user = request.user
        recruiter = Recruiter.objects.get(user=user)

        try:
            with transaction.atomic():
                 internship = Internship.objects.create(recruiter=recruiter, 
internship_title=internship_title, internship_mode=internship_mode, industry_type=industry_type, 
internship_desc=internship_desc, start_date=start_date, end_date=end_date, 
internship_deadline=internship_deadline, posted_date=date.today())
                for skill in skills:
                    InternshipSkill.objects.create(internship=internship, skill=skill)
        except Exception as e:
            print(e)

return render(request, 'post_internship.html', context)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题