Django database query: how to get an object by id?

Django automatically creates an id field as a primary key.

Now I need to get the object by this id.

object = Class.objects.filter() 

How to write this filter?

+80
django django-models django-orm
Nov 29 '10 at 2:14
source share
2 answers

If you want to get an object, using get() simpler:

 obj = Class.objects.get(pk=this_object_id) 
+148
Nov 29 '10 at 2:18
source share

I came here for the same problem, but for a different reason:

 Class.objects.get(id=1) 

An ImportError exception was thrown in this code. What baffled me was that the code below performed perfectly and returned the result set as expected:

 Class.objects.all() 

Trace tail for get() method:

 File "django/db/models/loading.py", line 197, in get_models self._populate() File "django/db/models/loading.py", line 72, in _populate self.load_app(app_name, True) File "django/db/models/loading.py", line 94, in load_app app_module = import_module(app_name) File "django/utils/importlib.py", line 35, in import_module __import__(name) ImportError: No module named myapp 

Reading the code inside Django loading.py , I came to the conclusion that my settings.py had the wrong path to my application, which contains my definition of the Class model. All I needed to do was the correct path to the application, and the get() method performed perfectly.

Here is my settings.py with the corrected path:

 INSTALLED_APPS = ( 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', # ... 'mywebproject.myapp', 

)

All the confusion was caused by the fact that I am using Django ORM as standalone, so the namespace should have reflected this.

+13
Sep 28 '13 at 17:55
source share



All Articles