Is possible to create a object and it's foreign key object with a single dictionary? #450
Answered
by
collerek
igormorgado
asked this question in
Q&A
-
If I only have a dictionary of a object ( item_dict = {
'name': 'ItemA',
'owner': {
'name': 'Person'
}
} Is possible to create the Item and Person with a single call? Or do I need to create from inside to outside? That is first I read A full functional snippet is below. The code "works" but, the import ormar as orm
import databases
import sqlalchemy
DATABASE_URL = 'sqlite:///db.sqlite'
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
class BaseMeta(orm.ModelMeta):
metadata = metadata
database = database
class Person(orm.Model):
class Meta(BaseMeta):
tablename = "persons"
id: int = orm.Integer(primary_key=True)
name: str = orm.String(max_length=32)
class Item(orm.Model):
class Meta(BaseMeta):
tablename = "items"
id: int = orm.Integer(primary_key=True)
name: str = orm.String(max_length=32)
owner: Person = orm.ForeignKey(Person)
async def create_db():
engine = sqlalchemy.create_engine(DATABASE_URL)
await database.connect()
metadata.drop_all(engine)
metadata.create_all(engine)
return metadata
async def tests():
item_dict = {
'name': 'ItemA',
'owner': {
'name': 'Person'
}
}
item_db = await Item.objects.create(**item_dict)
print(item_db.json())
persons = await Person.objects.all()
# No person here =/
for person in persons:
print(person.json(indent=2))
async def disconnect_db():
await database.disconnect()
async def main():
await create_db()
await tests()
await disconnect_db()
if __name__ == "__main__":
import asyncio
asyncio.run(main()) |
Beta Was this translation helpful? Give feedback.
Answered by
collerek
Nov 23, 2021
Replies: 1 comment 2 replies
-
Yes, check Note that it behaves differently if you provide pk value on related model (update) or not (insert). |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
igormorgado
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, check
save_related
method.Note that it behaves differently if you provide pk value on related model (update) or not (insert).