문제

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 ?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top