I am trying to save values for my Models through Django Shell . I am beginner in Django. I have crated three models. I inserted values in models one by one.i created Dept first and inserted all Dept Values.Created Student and inserted all student related values. Now i am trying to insert values in course which contains two foreign key studentId and dept id . How to insert values for Student model using 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)
Thank you for helping Jordan
You can insert the student and dept instances directly when inserting foreign key values:
student = Student.objects.last()
dept = Dept.objects.last()
course = Course.objects.create(courseName="My course", student=student, dept=dept)
.last() is the last one created, but you can get the instances however you like.
Also, you don't need to manually create primary keys. Django does it automatically for you. Each instance of a model has a pk value automatically assigned. That is if you don't need a differently named primary key. So the __str__ method in Course could be:
def __str__(self):
return '%s %s %s %s' % (self.courseId, self.courseName,self.student.pk,self.dept.pk)
I tried following syntax but unable to insert data. if i try to create null object like c1 = Course() and try to use that object it still gives error.
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)
Resulted in ""ValueError: "" needs to have a value for field "courseId" before this many-to-many relationship can be used."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With