Examples


Django Insert Data


Django provides an Object-Relational Mapping (ORM) system that allows you to interact with your database easily. You can use Django's shell to insert data into a model. The Python shell runs inside the virtual environment of your Django project.

To open a Python shell, use the command is given below:

python manage.py shell

Now we are in the shell, the result should be something like this:

D:\django_projects\myproject>python manage.py shell
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

Example

Insert a Single Record

Open the Django shell and execute the following code

After the three >>>, write the following at the bottom.

>>> from myapp.models import Product

To view the blank Product table, press [enter] and write this

>>> Product.objects.all()

This should give you an empty QuerySet object.

<QuerySet []>
  • A group of data from a database is called a QuerySet.
  • See the Django QuerySet chapter for more information on QuerySets.
  • Run these two lines to add a record to the table.
>>> product = Product(product_name='Apple',price=150,unit='Kg')
>>> product.save()

To view the inserted data

>>> Product.objects.all().values()

Output

<QuerySet [{'id': 1, 'product_name': 'Apple', 'price': 150.0, 'unit': 'Kg'}]>

Example

Insert Multiple Records

You can also insert multiple records at once

>>> product1 = Product(product_name='Orange', price=120.0, unit='Kg')
>>> product2 = Product(product_name='Strawberry', price=250.0, unit='Box')
>>> product3 = Product(product_name='Water Melon', price=90.0, unit='Piece')
>>> product_info = [product1,product2,product3]
>>> for record in product_info:
...     record.save()
...
>>>

To finish the for loop, hit [enter] one last time.

To see every record that has been added.

>>> Product.objects.all().values()

Output

<QuerySet [{'id': 1, 'product_name': 'Apple', 'price': 150.0, 'unit': 'Kg'}, 
{'id': 2, 'product_name': 'Orange', 'price': 120.0, 'unit': 'Kg'}, 
{'id': 3, 'product_name': 'Strawberry', 'price': 250.0, 'unit': 'Box'}, 
{'id': 4, 'product_name': 'Water Melon', 'price': 90.0, 'unit': 'Piece'}]>

Prev Next