Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django database query: How to get object by id?

People also ask

How can I get objects in Django?

Creating objects To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

How do I find my Django database ID?

Also FYI, id in a built-in function that returns the identity of an object. In a majority of cases referencing things by id will do the right thing e.g. Class. objects. get(id=this_object_id) work.

What is __ Str__ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

Does Django model have ID?

By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field.


If you want to get an object, using get() is more straightforward:

obj = Class.objects.get(pk=this_object_id)

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

Class.objects.get(id=1)

This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:

Class.objects.all()

Tail of the traceback for the 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's loading.py, I came to the conclusion that my settings.py had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.

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 because I am using Django's ORM as a standalone, so the namespace had to reflect that.


You can also use get_object_or_404 django shortcut. It raises a 404 error if object is not found.


You can also do:

obj = ClassModel.get_by_id(object_id)

This works, but there may I'm not sure if it's supported in Django 2.