Django Tutorial 6 – MyNotes App
Since we have created our mynotes models, we need to understand how Django uses that model to interact with database. This is achieved through ORM(Object Relational Mapping). This is nothing but the table entry is considered as an object and the create/read/update/delete happens through this object. Let’s see how to do this in the shell first. Then we will implement this in our project. To start Django shell, run the below command from mynotes settings folder.
(djangoenv) arockia@arockia-pc:~/Scripts/Python/eazytutor_work/mynotes/mynotes$ python manage.py shell Python 3.6.0 (default, Nov 22 2019, 17:04:24) [GCC 9.2.1 20191008] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>>
Now, import the models we created using below command
>>> from notesapp import models >>> dir(models) ['User', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'models', 'mynotes', 'note_tags', 'tags'] >>>
After the import you can notice that models has three classes which we created in models.py. Now, we can create one tag entry using the below command.
>>> tags_obj = models.tags() >>> tags_obj.tag_name='Django' >>> tags_obj.added_by_id=1 >>> tags_obj.save()
Now, we have created a single tag entry in tags model. This is how we create a model entry using Django ORM. Until you call .save() method on the newly created object from models class, the entry will not be saved in database. Now, we can see this tag from the admin panel as below.
You can see that it says “tags object(1)”. This is hard to interpret because if we want to see what’s this tag, we need to click on this and see the tag name. We need to add few changes to our models.py if we want to provide some meaningful representation while listing the Django objects. Update the tags model as below to do that.
class tags(models.Model): tag_id = models.AutoField(db_column='tag_id', primary_key=True) tag_name = models.TextField(db_column='tag_name', null=False, blank=False) added_date = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.tag_name
Now It’s more meaningful right?. Let’s resume the ORM stuff again. To list the objects we created from Django shell, use the below commands.
>>> tags_list = models.tags.objects.all() >>> tags_list <QuerySet [<tags: tags object (1)>]>
What is Queryset?
Queryset is the result type which ORM query returns. Through query set we can do get or set activities in database.
Queryset methods to search data:
- objects.get() – This method will expect at least one item which matches the criteria. If not, it raises exception.
- objects.filter() – This fetches all the records which matches the criteria. If there is no records, it returns None.
- objects.all() – This method will return all the records from the table.
>>> django_tag = models.tags.objects.get(tag_name__icontains = 'django') >>> django_tag <tags: tags object (1)> >>> django_tag.tag_name 'Django' >>>
You can see the exception which will be raised when your query returns nothing with objects.get() method beow.
>>> django_tag = models.tags.objects.get(tag_name__icontains = 'django1') Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/arockia/Scripts/Python/eazytutor_work/djangoenv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/arockia/Scripts/Python/eazytutor_work/djangoenv/lib/python3.6/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name notesapp.models.tags.DoesNotExist: tags matching query does not exist. >>>
models.filter() will not return that exception when you use the same query with this method.
>>> django_tag = models.tags.objects.filter(tag_name__icontains = 'django1') >>> django_tag <QuerySet > >>>
If you want to update your tag_name in this case, just fetch the object and update it’s tag_name attribute and call save() method. That’s it as below.
>>> django_tag = models.tags.objects.get(tag_name__icontains = 'django') >>> django_tag.tag_name='django1' >>> django_tag.save() >>> django_tag = models.tags.objects.get(tag_name__icontains = 'django') >>> django_tag.tag_name 'django1' >>>
Now, Spend some time to learn about queryset API in Django from this link . We will update our views.py in next lesson to create notes from our custom form instead of using Django Admin interface.