Question

Can someone please help me with this ManyToManyField issue

MODELS.PY

class Course(models.Model):
    course_code = models.CharField(max_length=8, unique=True)
    course_name = models.CharField(max_length=128, unique=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.course_code


class Degree(models.Model):
    degree_code = models.CharField(max_length=16, unique=True)
    degree_name = models.CharField(max_length=128, unique=True)
    courses = models.ManyToManyField(Course)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.degree_code

Now when I query

>>> Degree.objects.values_list('courses')
[(4,), (3,), (1,), (5,), (4,), (3,), (2,), (1,)]

I am getting IDs, how can I get the course name instead of ID ?

Was it helpful?

Solution

You may do this by accessing the fields of the related class thus:

Degree.objects.values_list('courses__course_name')

Documentation for Field lookups explains it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top