Django Clone

5.5.0 · active · verified Fri Apr 17

django-clone is a Django library that facilitates the creation of a deep clone of a Django model instance, including its related objects (Foreign Keys, One-to-One, Many-to-Many). It handles unique fields and provides flexibility for custom attribute overrides during cloning. The current version is 5.5.0, and it maintains an active development pace with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to clone a Django model instance using `clone_instance`. It creates a `Book` instance with a `ForeignKey` to `Author`, then clones the book, overriding the `isbn` (which is unique) and `title` to avoid conflicts. Note: A minimal Django setup is included for standalone runnability; in a real Django project, you'd omit `os.environ.setdefault` and `django.setup()`.

import os
from django.db import models
from django_clone import clone_instance

# Minimal Django setup for runnable example
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
import django
django.setup()

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    isbn = models.CharField(max_length=13, unique=True, null=True, blank=True)
    description = models.TextField(blank=True)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')

    def __str__(self):
        return self.title

# Create some initial instances
author1 = Author.objects.create(name="Jane Doe")
original_book = Book.objects.create(
    title="The Original Story", 
    isbn="1234567890123", 
    description="A timeless classic.", 
    author=author1
)

# Clone the book instance, providing a new unique ISBN
cloned_book = clone_instance(original_book, attrs={'isbn': '9876543210987', 'title': 'The Cloned Story'})

print(f"Original Book: {original_book.title} (ISBN: {original_book.isbn}, Author: {original_book.author.name})")
print(f"Cloned Book: {cloned_book.title} (ISBN: {cloned_book.isbn}, Author: {cloned_book.author.name})")

view raw JSON →