Skip to content

Delete data from database

The following methods allow you to delete data from the database.

  • delete(each: bool = False, **kwargs) -> int

  • model (作为商品类名时使用复数)

    • Model.delete() method
    • query set proxy

    • QuerysetProxy.remove() method

    • QuerysetProxy.clear() method

delete

delete(each: bool = False, **kwargs) -> int

QuerySet level deletion is used to delete multiple records at once.

You either have to filter the QuerySet first, or provide the each=True flag to delete the entire table.

If you do not provide this flag or filter, a QueryDefinitionError is raised.

Returns the number of deleted rows.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import asyncio

import databases
import ormar
import sqlalchemy
from examples import create_drop_database

DATABASE_URL = "sqlite:///test.db"

ormar_base_config = ormar.OrmarConfig(
    database=databases.Database(DATABASE_URL),
    metadata=sqlalchemy.MetaData(),
)


class Book(ormar.Model):
    ormar_config = ormar_base_config.copy(tablename="books")

    id: int = ormar.Integer(primary_key=True)
    title: str = ormar.String(max_length=200)
    author: str = ormar.String(max_length=100)
    genre: str = ormar.String(
        max_length=100,
        default="Fiction",
    )


@create_drop_database(base_config=ormar_base_config)
async def run_query():
    await Book.objects.create(
        title="Tom Sawyer", author="Twain, Mark", genre="Adventure"
    )
    await Book.objects.create(
        title="War and Peace in Space", author="Tolstoy, Leo", genre="Fantasy"
    )
    await Book.objects.create(
        title="Anna Karenina", author="Tolstoy, Leo", genre="Fiction"
    )

    # delete accepts kwargs that will be used in filter
    # acting in same way as queryset.filter(**kwargs).delete()
    await Book.objects.delete(genre="Fantasy")  # delete all fantasy books
    all_books = await Book.objects.all()
    assert len(all_books) == 2


asyncio.run(run_query())

model method

Each model instance has a set of methods to save, update, or load itself.

delete

You can delete a model instance by calling the delete() method.

!!!tip Read more about the delete() method in model methods

QuerysetProxy method

Returns a list of related models when directly accessing the related ManyToMany field and ReverseForeignKey.

But at the same time it exposes a subset of the QuerySet API, so you can filter, create, select related models, etc. directly from the parent model.

eliminate

Delete relevant models one by one.

Delete a relationship from the database.

If the keep_reversed flag is specified as Falseormar, the associated model is also deleted from the database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Album(ormar.Model):
    ormar_config = base_ormar_config.copy()

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)
    is_best_seller: bool = ormar.Boolean(default=False)

class Track(ormar.Model):
    ormar_config = base_ormar_config.copy()

    id: int = ormar.Integer(primary_key=True)
    album: Optional[Album] = ormar.ForeignKey(Album)
    title: str = ormar.String(max_length=100)
    position: int = ormar.Integer()
    play_count: int = ormar.Integer(nullable=True)


album = await Album(name="Malibu").save()
track1 = await Track(
    album=album, title="The Bird", position=1, play_count=30, 
).save()
# remove through proxy from reverse side of relation
await album.tracks.remove(track1, keep_reversed=False)

# the track was also deleted
tracks = await Track.objects.all()
assert len(tracks) == 0

eliminate

Delete all related models in one call.

Relationships in the database are also deleted.

Specifying the keep_reversed flag as Falseormar will also delete the associated model from the database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Album(ormar.Model):
    ormar_config = base_ormar_config.copy()

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)
    is_best_seller: bool = ormar.Boolean(default=False)

class Track(ormar.Model):
    ormar_config = base_ormar_config.copy()

    id: int = ormar.Integer(primary_key=True)
    album: Optional[Album] = ormar.ForeignKey(Album)
    title: str = ormar.String(max_length=100)
    position: int = ormar.Integer()
    play_count: int = ormar.Integer(nullable=True)


album = await Album(name="Malibu").save()
track1 = await Track(
    album=album, 
    title="The Bird", 
    position=1, 
    play_count=30, 
).save()
track2 = await Track(
    album=album,
    title="Heart don't stand a chance",
    position=2,
    play_count=20,
).save()

# removes the relation only -> clears foreign keys on tracks
await album.tracks.clear()

# removes also the tracks
await album.tracks.clear(keep_reversed=False)