models.py:
from django.db import models
class Course(models.Model):
course = models.TextField(blank=True)
class Student(models.Model):
first_name = models.TextField()
last_name = models.TextField()
course = models.ManyToManyField(Course)
forms.py:
from django import forms
from .models import Student, Course
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'course']
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ['course']
views.py:
def students_view(request):
if request.method == 'POST':
students_form = StudentForm(request.POST)
if students_form.is_valid():
students_form.save()
print(Student.objects.all().values())
students_form = StudentForm()
context = {
'form':students_form
}
return render(request, 'courses/courses.html', context)
If I print print(Student.objects.all().values())
than I see student's ID, first_name and last_name. But I don't see in which groups they belong to. How to print that?
CodePudding user response:
Like this for example:
students = Student.objects.prefetch_related("course")
print([(s, list(s.course.all()),) for s in students])