JIN
JIN

Reputation: 69

python django 'QuerySet' object has no attribute 'objects'

I am building a website using Python django. But, an error occurs while loading data using django ORM What's the problem?

model.py

class contact(models.Model):
    class Meta:
        db_table="contact"

    target = models.CharField(max_length=15)
    team = models.CharField(max_length=15)
    name = models.CharField(max_length=10)
    email = models.CharField(max_length=30)

view.py

@login_required(login_url='common:login')
def contact_list(request):
    global contact
    contact = contact.objects.values('target').annotate(count=Count('email')).order_by()
    context = {'contact': contact }
    return render(request, 'web/contact_list.html', context)

contact_list.html

{% if contact %}
{% for group in contact %}
<tr tabindex="0" class="h-16 border-b transition duration-300 ease-in-out hover:bg-gray-100">
 <td>
   <div class="mx-5 text-sm">
   {{ forloop.counter }} 
   </div>
 </td>
 <td class="">
   <div class="flex items-center pl-5">
     <a class="text-sm font-medium leading-none text-gray-700 dark:text-white mr-2">
     {{ group.target }}
     </a>
   </div>
 </td>
 <td class="pl-5">
   <div class="flex items-center">
    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
      <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
    </svg>
    <p class="text-sm leading-none text-gray-600 dark:text-gray-200 ml-2">{{ group.count }}</p>
   </div>
 </td>

trackback enter image description here

Upvotes: 1

Views: 912

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

Please do not use a global variable: you each time assign a new value to contact: the first time it is the contact model, the next time it is a queryset. Furthermore, global state [softwareengineering] is a severe antipattern, especially in web servers. Work with:

from app_name.models import Contact


@login_required(login_url='common:login')
def contact_list(request):
    targets = Contact.objects.values('target').annotate(
        count=Count('email')
    ).order_by('target')
    context = {'contact': targets}

Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from contact to Contact.

Upvotes: 1

Related Questions