6.3. ORM Create

  • .create()

  • .save()

  • .get_or_create()

  • .bulk_create()

6.3.1. Objects Create

  • QuerySet.create()

  • Customer.objects.create(firstname=..., lastname=...)

>>> john = Customer.objects.create(firstname='John', lastname='Doe')

6.3.2. Model Instance

  • Model.save()

>>> mark = Customer(firstname='Mark', lastname='Watney')
>>> mark.save()

It also allows for adding additional fields:

>>> melissa = Customer()
>>> melissa.firstname = 'Melissa'
>>> melissa.lastname = 'Lewis'
>>> melissa.save()

You can also mix the two:

>>> rick = Customer(firstname='Rick', lastname='Martinez')
>>> rick.birthdate = date(2000, 1, 2)
>>> rick.save()

A good practice is to use the .full_clean() method before calling .save().

>>> alex = Customer()
>>> alex.firstname = 'Alex'
>>> alex.lastname = 'Vogel'
>>> rick.full_clean()
>>> alex.save()

6.3.3. Get or Create

  • QuerySet.get_or_create()

When Mark Watney already exists in the database:

>>> mark, was_created = Customer.objects.get_or_create(
...     firstname='Mark',
...     lastname='Watney',
...     defaults={'is_verified': True},
... )
>>>
>>> mark
<Customer: Mark Watney>
>>>
>>> was_created
False

When Melissa Lewis does not exist in the database:

>>> melissa, was_created = Customer.objects.get_or_create(
>>>     firstname='Melissa',
>>>     lastname='Lewis',
>>>     defaults={'is_verified': True},
>>> )
>>>
>>> melissa
<Customer: Melissa Lewis>
>>>
>>> was_created
True

6.3.4. Bulk Create

  • QuerySet.bulk_create()

>>> customers = [
...     Customer(firstname='Mark', lastname='Watney'),
...     Customer(firstname='Melissa', lastname='Lewis'),
...     Customer(firstname='Rick', lastname='Martinez'),
...     Customer(firstname='Alex', lastname='Vogel'),
...     Customer(firstname='Beth', lastname='Johanssen'),
...     Customer(firstname='Chris', lastname='Beck'),
... ]
>>>
>>> Customer.objects.bulk_create(customers)
[<Customer: Mark Watney>, <Customer: Melissa Lewis>, <Customer: Rick Martinez>, <Customer: Alex Vogel>, <Customer: Beth Johanssen>, <Customer: Chris Beck>]

6.3.5. Create with ForeignKey

  • field=obj

  • field_id=value

If you have the customer_id:

>>> address = Address.objects.create(customer_id=1, **data)

If you don't have the customer_id:

>>> customer = Customer.objects.get(email=...)
>>> address = Address.objects.create(customer=customer, **data)

6.3.6. Create with ManyToMany

>>> customer = Customer.objects.get(email='mwatney@nasa.gov')
>>> products = Product.objects.filter(name='MyProduct')
>>>
>>> order = Order.objects.create(customer=customer)
>>> order.products.set(products)
>>> order.save()

6.3.7. Creation Counter

  • QuerySet.creation_counter

  • Customer.objects.creation_counter

>>> Customer.objects.creation_counter
13

6.3.8. Assignments

# doctest: +SKIP_FILE
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Database ORM Create
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 0. Use `myproject.shop`
# 1. Define variable `result` with result of ORM call for
#    create a new `Customer`:
#    - firstname: John
#    - lastname: Doe
# 2. Use `.create()` method

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Zdefiniuj zmienną `result` z wynikiem zapytania ORM dla
#    stworzenia nowego `Customer`:
#    - firstname: John
#    - lastname: Doe
# 2. Użyj metody `.create()`

# %% Hints
# - `.create()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'

>>> result
<Customer: John Doe>

>>> assert Customer.objects.filter(firstname='John', lastname='Doe').delete()
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

from shop.models import Customer


# Define variable `result` with result of ORM call for
# create a new `Customer`:
# - firstname: John
# - lastname: Doe
# Use `.create()` method
# type: Customer
result = ...


# doctest: +SKIP_FILE
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Database ORM Create
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 0. Use `myproject.shop`
# 1. Define variable `result` with result of
#    create a new `Customer` model instance with:
#    - firstname: John
#    - lastname: Doe
# 2. Use `.save()` method to add it do database

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Zdefiniuj zmienną `result` z wynikiem
#    stworzenia nowej instancji modelu `Customer` z:
#    - firstname: John
#    - lastname: Doe
# 2. Użyj metody `.save()` aby dodać go do bazy danych

# %% Hints
# - `.save()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'

>>> result
<Customer: John Doe>

>>> assert Customer.objects.filter(firstname='John', lastname='Doe').delete()
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

from shop.models import Customer


# Define variable `result` with result of
# create a new `Customer` model instance with:
# - firstname: John
# - lastname: Doe
# Use `.save()` method to add it do database
# type: Customer
result = ...


# doctest: +SKIP_FILE
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Database ORM Create
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3

# %% English
# 0. Use `myproject.shop`
# 1. Define variable `result` with result of ORM call for
#    getting `Customer` or create a new one if not exist:
#    - firstname: John
#    - lastname: Doe
# 2. Create instance and use `.get_or_create()` method
# 3. Mind, that method returns a two element tuple
#    but we need only a `Customer`

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Zdefiniuj zmienną `result` z wynikiem zapytania ORM dla
#    wyciągnięcia `Customer` lub stworzniem nowego jak nie istnieje:
#    - firstname: John
#    - lastname: Doe
# 2. Stwórz instancję modelu i użyj metodę `.get_or_create()`
# 3. Zwróć uwagę, że metoda zwraca dwu elementową tuplę
#    a potrzebny jest tylko `Customer`

# %% Hints
# - `.get_or_create()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'

>>> result
<Customer: John Doe>

>>> assert Customer.objects.filter(firstname='John', lastname='Doe').delete()
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

from shop.models import Customer


# Define variable `result` with result of ORM call for
# getting `Customer` or create a new one if not exist:
# - firstname: John
# - lastname: Doe
# Create instance and use `.get_or_create()` method
# Mind, that method returns a two element tuple
# but we need only a `Customer`
# type: Customer
result = ...


# doctest: +SKIP_FILE
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Database ORM Create
# - Difficulty: easy
# - Lines: 3
# - Minutes: 3

# %% English
# 0. Use `myproject.shop`
# 1. Define variable `result` with ORM methods call to
#    bulk create new `Customer`s:
#    - firstname: John, lastname: Doe
#    - firstname: Jane, lastname: Doe
# 2. Use `.bulk_create()` method

# %% Polish
# 0. Użyj `myproject.shop`
# 1. Zdefiniuj zmienną `result` z metodami ORM do
#        łącznego stworzenia nowych `Customer`:
#    - firstname: John, lastname: Doe
#    - firstname: Jane, lastname: Doe
# 2. Użyj metody `.bulk_create()`

# %% Hints
# - `.bulk_create()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'

>>> result
[<Customer: John Doe>, <Customer: Jane Doe>]

>>> assert Customer.objects.filter(firstname='John', lastname='Doe').delete()
>>> assert Customer.objects.filter(firstname='Jane', lastname='Doe').delete()
"""

# Required for Django to work
import os; os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django; django.setup()

from shop.models import Customer


# Define variable `result` with ORM methods call to
# bulk create new `Customer`s:
# - firstname: John, lastname: Doe
# - firstname: Jane, lastname: Doe
# Use `.bulk_create()` method
# type: QuerySet[Customer]
result = ...