Skip to content

Read data from database

The following methods allow you to load data from a database.

  • get(*args, **kwargs) -> Model

  • get_or_create(_defaults: Optional[Dict[str, Any]] = None, *args, **kwargs) -> Tuple[Model, bool]

  • first(*args, **kwargs) -> Model

  • all(*args, **kwargs) -> List[Optional[Model]]

  • iterate(*args, **kwargs) -> AsyncGenerator[Model]

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

    • Model.load() method
    • query set proxy

    • QuerysetProxy.get(*args, **kwargs) method

    • QuerysetProxy.get_or_create(_defaults: Optional[Dict[str, Any]] = None, *args, **kwargs) method
    • QuerysetProxy.first(*args, **kwargs) method
    • QuerysetProxy.all(*args, **kwargs) method

get

get(*args, **kwargs) -> Model

Get the first row from the database that satisfies the kwargs setting criteria.

If no condition is set, it returns the last row sorted by pk column in the database.

Passing a condition is actually calling the filter(*args, **kwargs) method described below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Track(ormar.Model):
    ormar_config = ormar.OrmarConfig(
        database=database,
        metadata=metadata,
        tablename="track"
    )

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


track = await Track.objects.get(name='The Bird')
# note that above is equivalent to await Track.objects.filter(name='The Bird').get()
track2 = track = await Track.objects.get()
track == track2
# True since it's the only row in db in our example
# and get without arguments return first row by pk column desc

!!!Warning A NoMatch exception is thrown if no rows satisfy the condition.

1
If there are multiple rows meeting the criteria the `MultipleMatches` exception is raised.

Get or None

get_or_none(*args, **kwargs) -> Model

Exactly the same as get described above, but returns None if no database record matching the condition is found instead of throwing an exception.

acquiring or creating

get_or_create(_defaults: Optional[Dict[str, Any]] = None, *args, **kwargs) -> Tuple[Model, bool]

A combination of create and get methods.

Attempts to get rows that meet the condition, and if a NoMatch exception is thrown, a new row is created with the given kwargs and_defaults.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Album(ormar.Model):
    ormar_config = base_ormar_config.copy(tablename="album")

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)
    year: int = ormar.Integer()


album, created = await Album.objects.get_or_create(name='The Cat', _defaults={"year": 1999})
assert created is True
assert album.name == "The Cat"
assert album.year == 1999
# object is created as it does not exist
album2, created = await Album.objects.get_or_create(name='The Cat')
assert created is False
assert album == album2
# return True as the same db row is returned

!!!warning Despite being equivalent rows in the database, album and album2 in the example above are 2 different python objects! Updating one of them does not refresh the second until you explicitly load () new data from the database.

Note that if you want to create a new object, you must either pass the pk column value or the pk column must be set to autoincrement

number one

first(*args, **kwargs) -> Model

Gets the first row sorted in ascending order by primary key column from the database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Album(ormar.Model):
    ormar_config = base_ormar_config.copy(tablename="album")

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)


await Album.objects.create(name='The Cat')
await Album.objects.create(name='The Dog')
album = await Album.objects.first()
# first row by primary_key column asc
assert album.name == 'The Cat'

all

all(*args, **kwargs) -> List[Optional["Model"]]

For filter options set, returns all rows in the database for a given model.

Passing kwargs is a shortcut equivalent to calling filter(*args, **kwargs).all().

If no rows meet the condition, an empty list is returned.

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

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)


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

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


tracks = await Track.objects.select_related("album").all(album__title='Sample')
# will return a list of all Tracks for album Sample
# for more on joins visit joining and subqueries section

tracks = await Track.objects.all()
# will return a list of all Tracks in database

iteration

iterate(*args, **kwargs) -> AsyncGenerator["Model"]

Returns an asynchronous iterable generator of all rows in the database for a given model.

Passing args and/or kwargs is a shortcut equivalent to calling filter(*args, **kwargs).iterate().

If no rows satisfy the condition, an empty asynchronous generator is returned.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Album(ormar.Model):
    ormar_config = base_ormar_config.copy(tablename="album")

    id: int = ormar.Integer(primary_key=True)
    name: str = ormar.String(max_length=100)


await Album.objects.create(name='The Cat')
await Album.objects.create(name='The Dog')
# will asynchronously iterate all Album models yielding one main model at a time from the generator
async for album in Album.objects.iterate():
    print(album.name)

# The Cat
# The Dog

!!!warns that using iterate() causes the previous prefetch_late () call to be ignored; these two optimizations don't make sense together.

1
If `iterate()` & `prefetch_related()` are used together the `QueryDefinitionError` exception is raised.

model method

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

to load

You can load the ForeignKey correlation model by calling the load() method.

Load() can be used to refresh the model from the database if it has been changed by another process.

!!!tip Read more about the load() method in Model Methods

QuerysetProxy method

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

But it also exposes a subset of the QuerySet API, so you can filter, create, select related models, and so on directly from the parent model.

get

It works exactly the same as the get function above, but allows you to get related objects from the other end of the relationship.

!!!tip To learn more about QuerysetProxy, visit the QuerysetProxy section

Get or None

Exactly the same as get described above, but returns None if no database record matching the condition is found instead of throwing an exception.

!!!tip To learn more about QuerysetProxy, visit the QuerysetProxy section

acquiring or creating

Identical to the get_or_create function above, but allows you to query or create related objects from the other end of the relationship.

!!!tip To learn more about QuerysetProxy, visit the QuerysetProxy section

number one

Exactly the same as the first function above, but allows you to query related objects from the other end of the relationship.

!!!tip To learn more about QuerysetProxy, visit the QuerysetProxy section

all

All the same functionality as above, but allows you to query related objects from the other end of the relationship.

!!!tip To learn more about QuerysetProxy, visit the QuerysetProxy section