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.
pip install django-cloneVerified import paths — ran on the pinned version, not inferred.
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()`.
Update your imports from `from django_clone.utils import clone_model_instance` to `from django_clone import clone_instance`.
Remove the `shallow` parameter from your `clone_instance` calls. If you need to prevent certain fields or relations from being cloned, use the `attrs` dictionary to set specific values or handle relationships manually after the clone operation, or use the provided signals for more advanced customization.
Always provide new unique values for unique fields via the `attrs` dictionary when cloning. For example: `clone_instance(original, attrs={'unique_field': 'new_unique_value'})`.Review the cloning behavior for related objects. If you need to link to existing related instances instead of creating new ones, or if related objects have unique constraints, you must manage these explicitly via the `attrs` dictionary, setting the ForeignKey/OneToOne field to an existing instance, or handle ManyToMany fields post-cloning. Use the `pre_clone_instance` and `post_clone_instance` signals for advanced control.