Django, matching query does not exist

Question:

I am new to Django. When I run the command python manage.py runserver on pycharm, I get the error message like

2017-12-03 05:09:56,952 - INFO - server - Listening on endpoint 
tcp_port=8000:interface=127.0.0.1
Internal Server Error: /
Traceback (most recent call last):
File "/Users/mac/anaconda/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in innerresponse = get_response(request)
File "/Users/mac/anaconda/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request)
File "/Users/mac/anaconda/lib/python3.6/site-packages/channels/handler.py", line 243, in process_exception_by_middleware
return super(AsgiHandler,self).process_exception_by_middleware(exception, request)
File "/Users/mac/anaconda/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/mac/PycharmProjects/590/flightmate/webapp/views.py", line 180, in index airlines = RecordSet.objects.get(name="airline")
File "/Users/mac/anaconda/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/mac/anaconda/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name
webapp.models.DoesNotExist: RecordSet matching query does not exist.

The code of models.py is :

from __future__ import unicode_literals
import uuid
import datetime
from django.db import models

class RecordSet(models.Model):
name = models.CharField(max_length=512)
value = models.TextField()
def __unicode__(self):
    return "{0}: {1}".format(self.name, self.value)

And the parent directory of models.py is the directory webapp. Any suggestions is appreciated, thanks!

Asked By: huier

||

Answers:

As you can see from the traceback, the issue is this:

airlines = RecordSet.objects.get(name="airline")

You are retrieving a single object with get() and since it does not exist, it returns DoesNotExist exception. This is also clearly mentioned in the Django documentation in the subchapter Retrieving a single object with get()

If there are no results that match the query, get() will raise a
DoesNotExist exception. This exception is an attribute of the model
class that the query is being performed on – so in the code above, if
there is no Entry object with a primary key of 1, Django will raise
Entry.DoesNotExist.

Either use filter() or get() with try ... except statement. You should use get() if you know that there is only one object that matches your query, otherwise use filter().

Answered By: Borut

in my case i fix this problem by trying this

i use filter() instead of get() so i resolve my problem. thanks for this answer

airlines = RecordSet.objects.filter(name="airline")
Answered By: user11074652

it’s a bit late to reply to this, but For those who have similar problems, there might be other reasons that this error occurs.
This can be occurred from ‘urls order or url names’

In my case, I was sending a post request through Ajax call to a url as below codes. even though I was sending the specific url for ‘topic favourite’ the urls.py addressed request to topic_view and the topic_view tries to match up a object with the topic_slug which is not given to the view function. it occurs the error matching query does not exist.

urls.py

path('topic/<slug:slug>/', views.topic_view, name='topic'),
path('topic/add/', views.topic_favorite_view, name='topic_favorite'),

.js

$.ajax({
        url: $(this).data('url'),
        type: 'POST',
        data:{
            csrfmiddlewaretoken: csrftoken,
            topic_slug: topicSlug,
            action: 'post',
        },
        success: function (res) {
            // console.log(res)
        },

So what I have done is changing the url order that put the topic_favorite above topic

path('topic/add/', views.topic_favorite_view, name='topic_favorite'),
path('topic/<slug:slug>/', views.topic_view, name='topic'),

or changed url name like this

'favorite/add/'
'topic/favorite/add/'
Answered By: Jondoe–

Load fixtures may solve this issue
for eg python manage.py loaddata initial_data user_groups states countries permissions notification

Answered By: Amina K M
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.