Django: Error matching query does not exist

This code throws me the error:

Matching query does not exist

Apparently the filter I have designed does not capture me the id of the orders.

Code:

models.py:

class Pedido(models.Model):
    especialidad   = models.ForeignKey('Especialidad')
    articulo       = models.ForeignKey('Articulo')
    fecha_entrega  = models.DateTimeField(auto_now_add=False)
    fecha_pedido   = models.DateTimeField(auto_now_add=True,null=True,     blank=True)
    cantidad       = models.IntegerField(blank=True)
    pendiente      = models.CharField(max_length=999,  null=True, blank=True)
    estado         =  models.CharField(max_length=20, blank=True, default='pendiente')

views.py 

def ArticuloListView(request, id_especialidad):
  user = request.user
  if user.is_superuser:
    pedido = Pedido.objects.get(id=id_especialidad)  #filtro de error
  else:
    pedido = Pedido.objects.filter(especialidad__encargado__usuario=user.id)
    template  = 'index2.html'
    return render_to_response(template,locals(), Context)

Here the url: (this if it captures the selected id)

url(r'^lista_esp/(?P<id_especialidad>\d+)/$', ArticuloListView, name="listar_esp"),

I don't know how to create a proper filter for what is required. Any help, please? Thanks in advance.

 2
Author: Pikoh, 2017-03-05

3 answers

What the error says is that the query has no results.

As there is always that risk, Django offers a shortcut called get_or_404 which sends users to the error page.

Of course, you can catch the exception (with try and catch) that is thrown and that is of type DoesNotExist, to give him another treatment.

 3
Author: toledano, 2017-03-05 23:12:16

I understand that what you want to do is get a single result from the queryset

pedido = Pedido.objects.get(id=id_especialidad)

While you can do what Angel indicates you can also handle it with .first () so that when it is an empty queryset it will return None and not an error like the one you indicate.

pedido = Pedido.objects.filter(id=id_especialidad).first()

Anyway it will depend on what you want to do, it would be better to handle the view that only receives post and can not modify that data from browser. The idea of using get_object_or_404 is good, but it depends on what you want.

 pedido = get_object_or_404(Pedido, id=id_especialidad)
 1
Author: Alvaro Aguilar, 2020-05-16 22:28:47

The source of your error is that the id you are trying to query does not exist in BD

pedido = Pedido.objects.get(id=id_especialidad)

To avoid this, and more when the id is being received from the url, I recommend doing a previous verification step, such as:

if Pedido.objects.filter(id=id_especialidad).exists():
    pedido = Pedido.objects.get(id=id_especialidad)
    # resto de acciones cuando el pedido existe
else:
    # acciones cuando el pedido no existe, redireccionas, envias un mensaje o cualquier opcion que consideres necesario para tratar este caso
    pass

And thus prevent any id that does not exist from breaking the application

Greetings

 0
Author: Angel F, 2017-03-20 13:14:39