Exception Value: The QuerySet value for an exact lookup must be limited to one result using slicing.

I have Academy and Professional_course model, the Professsional_course is related to Academy- ManyToMany relationship. Academy is related to User in ForeignKey. The challenge is that since Academy have User, i dont want to relate Professional_course again to User since it can access all the objects in Academy. I want the same user that have Academy to also have the Professional_course. Below is how i query it in my view and this error keep showing. I dont know exactly how to fix it.

this is my view

  def academy(request):
      credential =Academy.objects.filter(user_id =request.user).order_by('date_obtained')
      prof =Professional_course.objects.filter(academy =credential).order_by('date_obtained')
  
      if request.method == 'POST': 
          
          form =academyForm(request.POST,  request.FILES)
          form2 = professionalForm(request.POST, request.FILES)
  
          if form.is_valid(): 
              form.instance.user =request.user
              institution =form.cleaned_data.get('institution')
              certificate =form.cleaned_data.get('certificate_obtained')
              dates =form.cleaned_data.get('date_obtained')
              document =form.cleaned_data.get('document')
  
              form.save()
              try:
                  academy= Academy(user=request.user, institution = institution, certificate_obtained=certificate, date_obtained =dates, document =document)
                  
              except:
                  messages.error(request, 'Error saving data')
                  return redirect('academy')
              
  
          elif form2.is_valid():
              form2.instance.user =request.user  
              certificate2 =form.cleaned_data.get('certificate_obtained')
              certificate_no=form.cleaned_data.get('certificate_no')
              date =form.cleaned_data.get('date_obtained')
              doc =form.cleaned_data.get('document')
  
  
              
              form2.save()
                     
  
              try:
                  professio= Professional_course(certificate_no=certificate_no, 
                              certificate_obtained=certificate2, date_obtained =date, document =doc)
                  # professio.save()
                  professio.academy =request.user
                  professio.academy.add()
              except:
                  messages.error(request, 'Error saving your professional data!')
                  return redirect('academy')
  
          messages.success(request, 'User data saved successful! Click next to proceed')
          return redirect('academy')
          
      
      form = academyForm()
      form2 = professionalForm()
  
      context ={
          'form':form,
          'form2':form2,
          'credentials':credential,
          'profession':prof
      }
      
      return render(request, 'portal/home/credential.html', context )

this is the models

  class Academy(models.Model):
      user =models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank = True)
      institution =models.CharField(choices=ACADEMY_CHOICES, max_length=100, null=True, blank = True)
      certificate_obtained=models.CharField(choices=CERTIFICATE_CHOICES, max_length=100, null=True, blank = True)
      date_obtained =models.DateField(null =True, blank=True, default = 'YY-MM-DD')
      document = models.FileField(upload_to='document')
      # personalinfo =models.ForeignKey('Personalinfo', on_delete=models.CASCADE, null=True, blank = True)
      # job =models.ForeignKey('Job', on_delete=models.CASCADE, null=True, blank = True)
  
      def __str__(self):
          return self.certificate_obtained
  
  
  class Professional_course(models.Model):
      
      certificate_obtained =models.CharField(max_length=100, null=True, blank=True, default='Django')
      certificate_no =models.CharField(max_length=100, null=True, blank=True, default=2000)
      date_obtained =models.DateField(null =True, blank=True, default='2022-12-12')
      document = models.FileField(upload_to='profession document')
      academy = models.ManyToManyField(Academy)
  
      def __str__(self):
          return self.certificate_obtained

traceback:

  Microsoft Windows [Version 6.3.9600]
  (c) 2013 Microsoft Corporation. All rights reserved.
  
  C:\Users\Christopher\adamawa_civil_service_recruitment>python manage.py runserv
  er
  Watching for file changes with StatReloader
  Performing system checks...
  
  System check identified no issues (0 silenced).
  November 05, 2022 - 11:34:38
  Django version 4.0, using settings 'adamawa_civil_service_recruitment.settings'
  
  Starting development server at http://127.0.0.1:8000/
  Quit the server with CTRL-BREAK.
  Internal Server Error: /academy/
  Traceback (most recent call last):
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
      response = get_response(request)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
      response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "C:\Users\Christopher\adamawa_civil_service_recruitment\portal\views.py", line 129, in academy
      return render(request, 'portal/home/credential.html', context )
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\shortcuts.py", line 19, in render
      content = loader.render_to_string(template_name, context, request, using=using)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader.py", line 62, in render_to_string
      return template.render(context, request)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\backends\django.py", line 61, in render
      return self.template.render(context)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 176, in render
      return self._render(context)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 168, in _render
      return self.nodelist.render(context)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 977, in render
      return SafeString(''.join([
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 978, in <listcomp>
      node.render_annotated(context) for node in self
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 938, in render_annotated
      return self.render(context)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 153, in render
      return compiled_parent._render(context)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 168, in _render
      return self.nodelist.render(context)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 977, in render
      return SafeString(''.join([
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 978, in <listcomp>
      node.render_annotated(context) for node in self
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 938, in render_annotated
      return self.render(context)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\loader_tags.py", line 65, in render
      result = block.nodelist.render(context)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 977, in render
      return SafeString(''.join([
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 978, in <listcomp>
      node.render_annotated(context) for node in self
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\base.py", line 938, in render_annotated
      return self.render(context)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\template\defaulttags.py", line 171, in render
      len_values = len(values)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 262, in __len__
      self._fetch_all()
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1354, in _fetch_all
      self._result_cache = list(self._iterable_class(self))
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 51, in __iter__
      results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1189, in execute_sql
      sql, params = self.as_sql()
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 547, in as_sql
      where, w_params = self.compile(self.where) if self.where is not None else ('', [])
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 463, in compile
      sql, params = node.as_sql(self, self.connection)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\where.py", line 81, in as_sql
      sql, params = compiler.compile(child)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 463, in compile
      sql, params = node.as_sql(self, self.connection)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_lookups.py", line 135, in as_sql
      return super().as_sql(compiler, connection)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\lookups.py", line 331, in as_sql
      return super().as_sql(compiler, connection)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\lookups.py", line 210, in as_sql
      rhs_sql, rhs_params = self.process_rhs(compiler, connection)
    File "C:\Users\Christopher\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\lookups.py", line 313, in process_rhs
      raise ValueError(
  ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.
  [05/Nov/2022 11:35:02] "GET /academy/ HTTP/1.1" 500 211279

this is how i querry it in template

   {% for profs in profession %}
                        
                        <tr>
                          
                          <th scope="row">{{ forloop.counter }}</th>
                          
                          <td>{{ prof.certificate_obtained }}</td>
                          <td>{{ prof.certificate_no }}</td>
                          <td>{{ prof.date_obtained }}</td>
                          <td>{{ prof.document }}</td>
  
                        </tr>
                        {% endfor %}

please i need to assistance. Thanks

First, it’s not clear what you’re trying to model here. I’m not understanding what these Academy and Professional_course objects are, what they represent, or how they’re related to each other or the users in your system.

What is the real-life situation that you are attempting to represent within your system?

I believe the specific error you are reporting is related to this line:

The line before this one, the Academy query, can return multiple rows. This means that credential is not one object, it’s a queryset. However, this query is looking to do an exact match within the filter, causing this specific message:

Side notes:

These lines aren’t necessary. There’s no reason to have them in your code. (This is also true for the similar lines in your section of code for form2.)

The .save method of a form returns the instance of the model being saved.

Then there’s this:

This also doesn’t do anything. That line after the try is creating an instance of Academy, but it’s not saving it. Therefore, if an error were to be thrown by that line, it’s not because of there being an 'Error saving data'. The message is inaccurate because no attempt is being made to save anything.

Any time you have two forms on a page, you really should use a prefix for at least one of them.

Same comments as above regarding this not saving any data. Additionally, the academy field is a ManyToMany field with Academy. It makes no sense to assign request.user to it, and doing an empty add on that field doesn’t do anything for you either.

You don’t “query” anything in a template. The templates are just rendering data passed to it in the context. (The rendering engine may execute queries as a result of related field references.)

You have multiple field name reference issues. For example, in the template, you have:

But then inside your loop, you have lines like:

(Your iteration variable is named profs, but you’re referencing data by the name prof, which doesn’t match.)

Thanks for the quick response. My intension was to save academy as instance of professional_course so that through it I can access the User since it is related to User already.