Home > Back-end >  'QuerySet' object has no attribute 'id'
'QuerySet' object has no attribute 'id'

Time:10-26

I was building a django project in that I need to create an edit option for a particular model named SchoolDetail. But while fetching the data from this table using id, its showing the above error

views.py

def SchoolPage(request):
school_details = SchoolDetail.objects.all()
school_details_pk = school_details.id



context = {'school_details': school_details, 'school_details_pk':school_details_pk}
return render(request, 'busschool.html', context)

models.py

class SchoolDetail(models.Model):
school_name = models.CharField(max_length=100, blank= True, null=True)
school_place = models.CharField(max_length=100, blank= True, null=True)
school_email = models.CharField(max_length=100, blank= True, null=True)
school_address = models.CharField(max_length=100, blank= True, null=True)
school_phone = models.CharField(max_length=15, blank= True, null=True)
is_verified = models.BooleanField(default=False)

def __str__(self):
    return self.school_name

template

enter code here
<tbody>
                    {% for i in school_details %}
                    <tr>
                        <td>{{i.school_name}}</td>
                        <td>{{i.school_place}}</td>
                        <td>{{i.school_email}}</td>
                        <td>{{i.school_address}}</td>
                        <td>{{i.school_phone}}</td>
                        <td>{{i.is_verified}}</td>
                        <td><a href="{% url 'schooledit' school_details_pk %}">click</a></td>
                    </tr>
                    {% endfor %}
<tbody>

CodePudding user response:

The error is due to this row: school_details_pk = school_details.id. You can refer to the example for the first id:

school_details[0].id

Also iterate over all id in a loop:

for i in school_details:
    print(i.id)

CodePudding user response:

Thanks for all answers I find a solution

<tbody>
                    {% for i in school_details %}
                    <tr>
                        <td>{{i.school_name}}</td>
                        <td>{{i.school_place}}</td>
                        <td>{{i.school_email}}</td>
                        <td>{{i.school_address}}</td>
                        <td>{{i.school_phone}}</td>
                        <td>{{i.is_verified}}</td>
                        <td><a href="{% url 'schooledit' i.id %}">click</a></td>
                    </tr>
                    {% endfor %}
                </tbody>
  • Related