fix for not saving related model in reverse rel

This commit is contained in:
collerek
2021-06-02 13:05:10 +02:00
parent 0254abcd6c
commit c8ca6edb22
5 changed files with 63 additions and 2 deletions

Binary file not shown.

View File

@ -0,0 +1,54 @@
from typing import Optional
import databases
import pytest
import sqlalchemy
import asyncio
import ormar
from tests.settings import DATABASE_URL
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
class Department(ormar.Model):
class Meta:
database = database
metadata = metadata
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
class Course(ormar.Model):
class Meta:
database = database
metadata = metadata
id: int = ormar.Integer(primary_key=True)
name: str = ormar.String(max_length=100)
completed: bool = ormar.Boolean(default=False)
department: Optional[Department] = ormar.ForeignKey(Department)
@pytest.fixture(autouse=True, scope="module")
def create_test_database():
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.drop_all(engine)
metadata.create_all(engine)
yield
metadata.drop_all(engine)
@pytest.mark.asyncio
async def test_adding_relation_to_reverse_saves_the_child():
async with database:
department = await Department(name="Science").save()
course = Course(name="Math", completed=False)
await department.courses.add(course)
assert course.pk is not None
assert course.department == department
assert department.courses[0] == course