데이터베이스의 데이터 업데이트
다음 방법 및 기능을 사용하면 데이터베이스의 기존 데이터를 업데이트할 수 있습니다.
-
update(each: bool = False, **kwargs) -> int
-
update_or_create(**kwargs) -> Model
-
bulk_update(objects: List[Model], columns: List[str] = None) -> None
-
모델
업데이트
update(each: bool = False, **kwargs) -> int
쿼리 세트 수준 업데이트는 한 번에 동일한 값으로 여러 레코드를 업데이트하는 데 사용됩니다.
전체 테이블을 업데이트하려면 먼저 쿼리 세트를 필터링하거나 각 = 참 플래그를 제공해야 합니다.
이 플래그 또는 필터를 제공하지 않으면 QueryDefinitionError 올라갑니다.
업데이트된 행 수를 반환합니다.
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", author="Tolstoy, Leo", genre="Fiction"
)
await Book.objects.create(
title="Anna Karenina", author="Tolstoy, Leo", genre="Fiction"
)
await Book.objects.update(each=True, genre="Fiction")
all_books = await Book.objects.filter(genre="Fiction").all()
assert len(all_books) == 3
asyncio.run(run_query())
|
!!!경고, 실수로 덮어쓰는 것을 방지하기 위해 업데이트하기 전에 쿼리 세트를 필터링해야 합니다.
| 전체 데이터베이스 테이블을 업데이트하려면 `each=True` 를 안전 스위치로 제공해야 합니다.
|
업데이트 또는 생성
update_or_create(**kwargs) -> Model
모델을 업데이트하거나 데이터베이스에 일치하는 모델이 없는 경우 새 모델을 만듭니다.
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 | 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()
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", author="Tolstoy, Leo", genre="Fiction"
)
await Book.objects.create(
title="Anna Karenina", author="Tolstoy, Leo", genre="Fiction"
)
# if not exist the instance will be persisted in db
vol2 = await Book.objects.update_or_create(
title="Volume II", author="Anonymous", genre="Fiction"
)
assert await Book.objects.count() == 4
# if pk or pkname passed in kwargs (like id here) the object will be updated
assert await Book.objects.update_or_create(id=vol2.id, genre="Historic")
assert await Book.objects.count() == 4
asyncio.run(run_query())
|
새 개체를 만들려면 pk 열 값을 전달하거나 pk 열을 자동 증분으로 설정해야 합니다.
배치 업데이트
bulk_update(objects: List["Model"], columns: List[str] = None) -> None
여러 인스턴스를 동시에 업데이트할 수 있습니다.
통과된 모든 모델은 기본 키 열로 채워져야 합니다.
열 목록을 문자열 이름 목록으로 전달하여 업데이트할 필드를 선택할 수도 있습니다.
| # bulk_create에서 예제를 계속합니다.
# 개체 업데이트
todos의 경우:
Todo. = 거짓
# 모든 개체의 업데이트를 한 번에 수행
# 개체에는 pk 열이 설정되어 있어야 합니다. 그렇지 않으면 예외가 발생합니다.
ToDo.ts.bulk_(todo)를 기다리십시오.
완료 = ToDo.ts.filter (완료 = 거짓).all ()
주장 렌 (완료) == 3
|
모델 방법
각 모델 인스턴스에는 저장, 업데이트 또는 로드하는 일련의 방법이 있습니다.
업데이트
모델의 속성(필드)을 업데이트하고 업데이트() 메서드를 호출하여 모델을 업데이트할 수 있습니다.
기본 키를 설정하지 않고 모델을 업데이트하려고 하면 ModelPersistenceError 예외가 발생합니다.
!!!팁 모델의 업데이트() 방법에 대해 자세히 알아보기 - 업데이트
업데이트 삽입
모델의 저장() 또는 업데이트(**kwargs) 메서드의 프록시입니다. pk가 설정되면 업데이트() 메서드가 호출됩니다.
!!!팁 모델-업퍼트의 업퍼트() 방법에 대해 자세히 알아보십시오.
관련 저장
메소드는 메소드를 호출하고 저장되지 않은 각 모델에서 up() 메서드를 호출하는 모델의 모든 관계를 반복합니다.
!!!팁 모델 저장 지연의 저장 _lated() 방법에 대해 자세히 알아보십시오.
QuerysetProxy 방법
관련 ManyTo많이 필드 및 ReverseForeignKey에 직접 액세스하면 관련 모델 목록이 반환됩니다.
그러나 쿼리 세트 API의 하위 집합도 표시되므로 상위 모델에서 직접 필터링, 생성, 관련 모델 선택 등을 할 수 있습니다.
업데이트 또는 생성
업데이트 _ 또는 _ 생성 함수는 위와 정확히 동일하지만 관계의 다른 쪽 끝에서 관련 개체를 업데이트하거나 만들 수 있습니다.
!!!QuerysetProxy에 대해 자세히 알아보려면 QuerysetProxy 섹션을 방문하십시오.