Django模型 - 使用Shell插入外键值



我正在尝试通过django shell为模型保存值。我是Django的初学者。我已经板条三个型号。我将值插入模型中。我首先创建了部门并插入了所有部门值。创建的学生并插入了所有与学生相关的值。现在,我试图将值插入当然包含两个外国关键学生ID和部门ID。如何使用django shell插入学生模型的值。

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

谢谢您的帮助乔丹

您可以在插入外键值时直接插入学生并直接插入实例:

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

.last()是最后一个创建的,但是您可以按照自己的意愿获得实例。


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

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

我尝试了遵循语法,但无法插入数据。如果我尝试创建诸如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:"需要在这种多一到多的关系之前都有一个字段"课程"的价值。"

我想我发现了如何做。

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

`需要以单独的步骤进行操作。我不确定我是否可以同时保存部门和学生。乔丹

最新更新