How to Copy Django Model Instance Objects

Models in Django Rest Framework provide the user an ease to handle databases. In Django the user does not even have to write the SQL query to create or alter tables, just create the model, run some commands and it will create the table for you, that’s the beauty of Django. In this blog, we will learn about how to copy Django model instance objects. But before moving ahead let’s have a sneak peek about models.

How to Copy Django Model Instance Objects

What is a Model?

A table in our database is represented by the classes in our models. Every member of the class is a field of the table. We create models in the app > models.py file. Example of a model is shown below:-

from django.db import models
# Create your models here.
class Employee(models.Model):
    name=models.CharField(max_length=50)
    salary=models.IntegerField()

Here Employee is the table name, name and salary are the attributes of the table, where name can store only character value whose maximum length is 50 and salary can store only integer value.

Procedure to Copy Django Model Instance Objects

Here, is the abstract explanation about steps to copy Django model instance objects.

  1. Create a model
  2. Make an html file
  3. Define a function
    1. Create an object of model
    2. Copy the model instance
  4. Provide the path for the function

Implementation

Step1. Create a model

  1. Create a model in your app >models.py file, here in this example I had created a model named Student.

Models.py

from django.db import models
# Create your models here.
class Student(models.Model):
    name=models.CharField(max_length=50)
    age=models.IntegerField()
    country=models.CharField(max_length=50)

2. Add a database to your project by adding the following code in your project > settings.py file.

Settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'bloglogindecorator',
        'USER': 'postgres',
        'PASSWORD':"2320",
        'HOST': 'localhost'
    }
}

3. Run the following code in your command prompt one by one to migrate your model.

python manage.py makemigrations

Note:- Please change logindecorator to your app name while running the second command.

python manage.py sqmigrate logindecorator 0001

python manage.py migrate


Step2. Provide Url path to the function in app> urls.py file.

Urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('blogcopymodel',views.blogcopymodel,name="blogcopymodel")
]

Step3. Create a Function

  First we will just create an object of the normal model and pass it to the html file.

  1. Import your model.
  2. Define a function in app > views.py file.
  3. Make an instance or object of the model, pass the parameters and save the model.
  4. Get the object of that model 
  5. Pass it to the html file.

Views.py

from django.shortcuts import render
from .models import Student
 
def blogcopymodel(request):
    student=Student(name="Akshay", age=24,country="India")
    student.save()
    return render(request,'blogcopymodel.html',{'s1':s1})

Blogcopymodel.html

<html>
<head>
    <title>BlogCopyModel</title>
</head>
<body>
    <h1>Name:{{s1.name}}</h1>
    <h1>Age:{{s1.age}}</h1>
    <h1>Country:{{s1.country}}</h1>
    </body>
</html>

Output :-

How to Copy Django Model Instance Objects

Now, We will copy django model instance objects

  1. Copy the object.
  2. Instantiate the values and pass it to the html file

Views.py

from django.shortcuts import render
from .models import Student
def blogcopymodel(request):
    s1=Student.objects.get(pk=1)
    s2=s1
    s2.name="Akriti"
    s2.age=24
    s2.country="America"
    return render(request,'blogcopymodel.html',{'s1':s1,'s3':s3})

Blogcopymodel.html

<html>
<head>
    <title>BlogCopyModel</title>
</head>
<body>
    <h1>Name:{{s1.name}}</h1>
    <h1>Age:{{s1.age}}</h1>
    <h1>Country:{{s1.country}}</h1>
    <h1>Name:{{s2.name}}</h1>
    <h1>Age:{{s2.age}}</h1>
    <h1>Country:{{s2.country}}</h1>
</body>
</html>

Output:-

How to Copy Django Model Instance Objects

See, we had copy the objects successfully, in above picture values of both the objects are changed as we change the value of copied object

Now, We will copy the django model instance object and instantiate its values without changing the actual object.

  1. Get the object and store it into new object
  2. Change its id and pk (primary key) equals to none so that django will create it automatically.
  3. Now change the values of the newly created object
  4. Pass it to the html

Views.py

from django.shortcuts import render
from .models import Student
def blogcopymodel(request):
    s3=Student.objects.get(pk=1)
    s3.pk=None
    s3.id=None
    s3.name="Varun"
    s3.age=31
    s3.country="Africa"
    s3.save()
    s1=Student.objects.get(pk=1)
    return render(request,'blogcopymodel.html',{'s1':s1,'s3':s3})

Blogcopymodel.html

<html>
<head>
    <title>BlogCopyModel</title>
</head>
<body>
    <h1>Name:{{s1.name}}</h1>
    <h1>Age:{{s1.age}}</h1>
    <h1>Country:{{s1.country}}</h1>
    <h1>Name:{{s3.name}}</h1>
    <h1>Age:{{s3.age}}</h1>
    <h1>Country:{{s3.country}}</h1>
</body>
</html>

Output :-

How to Copy Django Model Instance Objects

See, we had copied the object without making any changes in the previous object’s value.

Conclusion

So, we had learned how to copy Django model instance object. I hope this blog will be useful for you and helps you to understand each and every step. Hope all your doubts get cleared. Thank you.