django queryset values() to string or json

Viewed 518

I'm trying to convert my dict to a list of string. this is what generated by django froms list of student

I want to have a list without the {''} My forms :

    students= ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(
    attrs={'class': 'displaynone'}),
    queryset=Student.objects.exclude(present=True).order_by(
        'name').values('name'),
    required=False,
    label="Choice Students"
)

and template

{% for i in form.students %}
  {{ i }}
{% endfor %}

and I know I can juste do queryset=Student.objects.exclude(present=True).order_by('name') without the values() but I juste want to retreive the name. It will optimize the load of my page.

3 Answers

You can use only to specify certain fields you want to fetch from the database, if you subsequently access a field that was not included in only() this will then cause a query to be run

queryset=Student.objects.exclude(present=True).order_by('name').only('name', 'id')

yeah it's working well, but my load is the same. I think its because i also retreive the classes in my template. like

<td class="class-name">{% for j in i.data.value|get_classes %}{{ j }}<br/>{% endfor %}</td>

and I use custom tags to retreive classes

def get_classes(student):
mystudent = Student.objects.get(pk=student)
list_student = list()
for i in mystudent.classe_set.all():
    list_student.append(i.name)
return list_student

this is my template.

<table class="table" id="student_table">
<thead>
    <tr>
        <th scope="col">Student(s)</th>
        <th scope="col">Classe(s)</th>
    </tr>
</thead>
{% for i in form.student %}
    <tr class="click_student">
        <td>{{ i}}</td>
        <td class="schedule-name">{% for j in i.data.value|get_classes %}{{ j }}<br/>{% endfor %}</td>
    </tr>
{% endfor %}

and this what it's look like. student with their classes

there is a relationship between student and class.

Related