Django: Error matching query does not exist

1

This code throws me the error:

  

matching query does not exist

Apparently the filter I have designed does not capture 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 you capture the id selected)

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

I do not know how to create an adequate filter for what is required. Any help please? Thanks in advance.

    
asked by Demaro Create 05.03.2017 в 23:43
source

2 answers

2

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 that sends users to the error page.

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

    
answered by 06.03.2017 в 00:12
0

The origin of your error is that the id you are trying to consult 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 you do a previous step of verification, 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 so avoid any id that does not exist to break the application

Greetings

    
answered by 20.03.2017 в 14:14