Django Models - 使用Shell插入外键值

时间:2018-02-07 12:09:13

标签: django django-models

我正在尝试通过Django Shell为我的模型保存值。我是Django的初学者。我有三个模型。我逐个在模型中插入值。我首先创建了Dept并插入了所有Dept Values.Created学生并插入了所有与学生相关的值。现在我试图在包含两个外键studentId和dept id的过程中插入值。如何使用Django Shell为Student模型插入值。

    # -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models

# Create your models here.
from django.db import models
from django.utils import timezone

class Student(models.Model):
    studentId = models.AutoField(primary_key=True)
    firstname = models.CharField(max_length=50)
    middlename = models.CharField(max_length=1)
    lastname = models.CharField(max_length=50)
    city = models.CharField(max_length=200)
    registe_dt = models.DateTimeField(default=timezone.now())
    def __str__(self):
        return '%s %s %s' % (self.studentId, self.firstname,self.city)


class Dept(models.Model):
    deptId = models.AutoField(primary_key=True)
    deptName = models.CharField(max_length=200)
    def __str__(self):
        return '%s %s' % (self.deptId, self.deptName)

class Course(models.Model):
    courseId=models.AutoField(primary_key=True)
    courseName=models.CharField(max_length=100)
    student = models.ManyToManyField(Student)
    dept = models.ForeignKey(Dept,on_delete=models.CASCADE)
    def __str__(self):
        return '%s %s %s %s' % (self.courseId, self.courseName,self.student.primary_key,self.dept.primary_key)

感谢您的帮助 约旦

3 个答案:

答案 0 :(得分:2)

插入外键值时,可以直接插入student和dept实例:

student = Student.objects.last()
dept = Dept.objects.last()

course = Course.objects.create(courseName="My course", student=student, dept=dept)

.last()是最后创建的,但您可以随意获取实例。

此外,您无需手动创建主键。 Django会自动为您完成。模型的每个实例都会自动分配pk值。也就是说,如果您不需要使用不同名称的主键。因此__str__中的Course方法可以是:

def __str__(self):
        return '%s %s %s %s' % (self.courseId, self.courseName,self.student.pk,self.dept.pk)

答案 1 :(得分:0)

我尝试了以下语法,但无法插入数据。 如果我尝试创建像c1 = Course()这样的空对象并尝试使用该对象,它仍然会出错。

s1 = Student(firstname='test',middlename='M',lastname='test',city='test') s1.save() for dept: d1 = Dept(deptName='Computer') d1.save() for course: course = Course.objects.create(courseName='Java',student=s1,dept=d1)

导致"" ValueError:""需要有一个领域的价值" courseId"在此之前可以使用多对多关系。"

答案 2 :(得分:0)

我想我发现了怎么做。 `

  c1 = Course(courseName='Java',dept=d1)
   c1.save()
   c1.student.add(s1)
   c1.save()

` 需要在单独的步骤中进行。我不确定我是否可以在课程中同时保存部门和学生。 约旦