File: insert.md

package info (click to toggle)
python-beanie 2.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,480 kB
  • sloc: python: 14,427; makefile: 7; sh: 6
file content (60 lines) | stat: -rw-r--r-- 1,649 bytes parent folder | download | duplicates (2)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
# Insert the documents

Beanie documents behave just like pydantic models (because they subclass `pydantic.BaseModel`).
Hence, a document can be created in a similar fashion to pydantic:

```python
from typing import Optional

from pydantic import BaseModel

from beanie import Document, Indexed


class Category(BaseModel):
    name: str
    description: str


class Product(Document):  # This is the model
    name: str
    description: Optional[str] = None
    price: Indexed(float)
    category: Category

    class Settings:
        name = "products"


chocolate = Category(name="Chocolate", description="A preparation of roasted and ground cacao seeds.")
tonybar = Product(name="Tony's", price=5.95, category=chocolate)
marsbar = Product(name="Mars", price=1, category=chocolate)
```

This however does not save the documents to the database yet.

## Insert a single document

To insert a document into the database, you can call either `insert()` or `create()` on it (they are synonyms):

```python
await tonybar.insert()
await marsbar.create()  # does exactly the same as insert()
```
You can also call `save()`, which behaves in the same manner for new documents, but will also update existing documents. 
See the [section on updating](updating-&-deleting.md) of this tutorial for more details.

If you prefer, you can also call the `insert_one` class method: 

```python
await Product.insert_one(tonybar)
```

## Inserting many documents

To reduce the number of database queries, 
similarly typed documents should be inserted together by calling the class method `insert_many`:

```python
await Product.insert_many([tonybar,marsbar])
```