Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print many-to-many field

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

Like this for example:

students = Student.objects.prefetch_related("course")

print([(s, list(s.course.all()),) for s in students])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading