模型和查询集

时间:2018-03-16 09:50:41

标签: django django-models django-forms django-templates django-views

我正在尝试制作一个简单的应用程序,但似乎面临着问题。我在学生和课程之间创建了许多对象,并且还定义了dept。 我的模型如下所述:

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

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

class Student(models.Model):
    stuName = models.CharField(max_length=100)
    stuCity = models.CharField(max_length=100)
    stuPhone = models.IntegerField(max_length=10)
    stuNationality = models.CharField(max_length=50)
    stuCreatedt = models.DateTimeField(default=timezone.now)
    def __str__(self):
        return '%s %s %s' % (self.stuName,self.stuCity,self.stuNationality)

我的表格是:

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        fields = ('stuName','stuCity','stuPhone','stuNationality','stuCreatedt')


class CourseForm(forms.ModelForm):
    class Meta:
        model = Course
        fields = ('courseId','courseName','enrolledStu','students','dept')


class DeptForm(forms.ModelForm):
    class Meta:
        model = Dept
        fields = ('deptId','deptName')

我已经在html模板中显示了课程列表,学生和部门,现在我正在尝试使用代码编辑它:

def edtStudent(request,pk):
    course = Course.objects.filter(pk=1).prefetch_related('students').select_related('dept').get()
    if request.method =="POST":
        form = CourseForm(request.POST,instance=Course)
        if form.is_valid():
           course = form.save(commit=False)
           print(form.cleaned_data)
           course.courseName = request.POST['courseName']
           course.enrolledStu = request.Post['enrolledStu']
           course.save()
           course.save_m2m()
           return redirect('liststudent')
    else:
        print(course.__dict__)
        print(course.students)
        #form = CourseForm()
        #return render(request, 'stuApp/edtStudent.html', {'form':form})
        #form = CourseForm(instance=course[0]) worked
        form = CourseForm(instance=course)
        return render_to_response('stuApp/edtStudent.html', {'form': form})

因此,我没有找到一名学生,而是让所有学生参加课程..似乎我的查询不正确。你能帮帮忙..

我的另一个问题是如何在多对多的关系中打印对象的值...现在,如果我打印课程对象,我会得到像

这样的结果
{'_state': <django.db.models.base.ModelState object at 0x000000000457ED68>, 'courseId': 1, 'courseName': 'Account', 'enrolledStu': 1, 'dept_id': 1, '_dept_cache': <Dept: 1 Finance>, '_prefetched_objects_cache': {'students': <QuerySet [<Student: Mamta Mumbai Indian>]>}}

...

所以从查询集我想只取学生名字......

约旦

1 个答案:

答案 0 :(得分:0)

我已经跟进了这个问题..当我尝试编辑html模板的课程时,它获取的值是正确的,但对于学生来说,它获取所有属性,如studentname,city,natinality等..哪个错误..我只想要学生的学生姓名并在模板中显示。 我正在使用以下查询来获取课程相关信息。

course = Course.objects.filter(pk=1).prefetch_related('students').select_related('dept').get()

getting results from query but for student it gets all attribute

现在在我看来我正在使用这段代码:

course = Course.objects.filter(pk=1).prefetch_related('students').select_related('dept').get()
    form = CourseForm(instance=course)
    return render_to_response('stuApp/edtStudent.html', {'form': form})

我想出了如何获得学生姓名而不是所有属性的价值。

course.students = course.students.value_list('stuName', flat=True)

但我不知道如何设置上面的值来形成并在模板中显示它。 这就是我失败的地方..