Inserting, deleting and updating data using Django ORM
In this tutorial, We are going to learn about inserting, deleting, updating data using Django-ORM. For this tutorial. I have used Pycharm for executing the code. You can any platform. firstly you need to install Django by using this command “pip install Django”. Before entering into the topic, know the basics like how to create the model, how to access the server etc. You can read about the basics here Creating Django Models and their Tables in the database(Part V)
Let’s have a look at the model.
class Blog(models.Model): name=models.CharField(max_length=50) tagline=models.TextField() def __str__(self): return self.name class Author(models.Model): name=models.CharField(max_length=50) email=models.EmailField() def __str__(self): return self.name class Entry(models.Model): blog=models.ForeignKey(Blog,on_delete=models.CASCADE) headline=models.CharField(max_length=255) body_text=models.TextField() publish_date=models.DateField() authors=models.ManyToManyField(Author) rating=models.IntegerField() def __str__(self): return self.headline
I have created three tables Blog, Author, Entry. Schema of this database model :
Blog(name, tagline).
Author(name, email).
Entry(blog, headline, body_text, publish_date, authors, rating) blog as Foreign key.
we access the Django ORM by typing the following command in the project directory
python manage.py shell
We can import our models by the following line.
from posts.models import Blog, Author, Entry
Adding data to the model
To create an object of the model Blog and save it into the database below is the Python code:
a=Blog(name="Human Being",tagline="Man is a social animal") a.save()
likewise, you can add objects to the other models also.
Let’s add some more objects to the Blog model.
a=Blog(name="Food",tagline="food is very essential for survival") a.save() a=Blog(name="Codespeedy",tagline="We are always developing and researching something new to gear up the technology.") a.save()
Let’s see all the objects
>>> Blog.objects.all() <QuerySet [<Blog: Human Being>, <Blog: Food>, <Blog: Codespeedy>]>
Updating or Modifying the data
Let’s update the tagline of the blog named “Codespeedy”. We can do it by.
>>> a=Blog.objects.get(pk=3) >>> a.tagline="Provide free blog posts and tutorial on programming language and code snippets." >>> a.save()
pk is short for the primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key.
Deleting the data
We can delete the object by the following lines.
>>> a=Blog.objects.get(pk=2) >>> a.delete() (1, {'posts.Blog': 1}) >>> Blog.objects.all() <QuerySet [<Blog: Human Being>, <Blog: Codespeedy>]>
You can see that blog named Food has been deleted.
Leave a Reply