A
A
AkiroToshiro2020-11-18 18:55:48
Django
AkiroToshiro, 2020-11-18 18:55:48

How to pull data from django database?

I have create classes which are linked by
models.py

class Lesson(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name


class StudentsGroup(models.Model):
    name = models.CharField(max_length=10)
    lessons = models.ManyToManyField(Lesson)

    def __str__(self):
        return self.name


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    student_group = models.ForeignKey(StudentsGroup, blank=True, null=True, on_delete=models.SET_NULL)

views.py
def lessons(request):
    get_profile = Profile.objects.get(id = request.user.id)
    get_group = StudentsGroup.objects.all()
    get_lessons = Lesson.objects.all()
    context = {
        'get_lesson': get_lessons,
        'get_group': get_group,
        'get_profile': get_profile,
    }
    template = 'core/lessons.html'
    return render(request, template, context)

lessons.html
<p> Lessons: </p> <br>
{{get_profile}}
{{get_profile.student_group.lessons}}

I want to display a list of items that are linked to the group to which the profile is linked, but it displays something incomprehensible: 5fb543f7beae5679402418.png
What am I doing wrong with the output?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2020-11-18
@AkiroToshiro

What is incomprehensible?
The profile object (1) is your {{get_profile}} (you didn't define the __str__() method on the model, it's inferred by default).
get_profile.student_group.lessons will return a string representation of the associated Lesson object manager. If you want a list, do a loop:

{% for lesson in get_profile.student_group.lessons.all %}{{ lesson.name }}<br>{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question