Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

not work ForeignKeyField #305

Closed
fruitoiz opened this issue Nov 23, 2024 · 1 comment
Closed

not work ForeignKeyField #305

fruitoiz opened this issue Nov 23, 2024 · 1 comment

Comments

@fruitoiz
Copy link

when using ForeignKeyField in peewee_async the code fails with an error. It says that you need to use .set_allow_sync(), but I need the asynchronous option

при использовании ForeignKeyField в peewee_async код завершается ошибкой. Написано что нужно использовать .set_allow_sync(), но мне нужен асинхронный вариант

example code on peewee where everything works fine:

пример кода на peewee где все работает исправно:

from peewee import *

db = SqliteDatabase(':memory:')

class BaseModel(Model):
    class Meta:
        database = db

class Favorite(BaseModel):
    text = TextField()

class Tweet(BaseModel):
    user_id = IntegerField()
    name = TextField()
    favorite = ForeignKeyField(Favorite, backref='favorites')

db.create_tables([
    Favorite,
    Tweet
])

info_favorite = Favorite.create(text="text uwu")
Tweet.create(user_id=11, favorite=info_favorite, name="Durov")

info = Tweet.get(user_id=11)
print(info.name) # Durov
print(info.favorite.text) # text uwu

example code for peewee-async where this functionality does not work:

пример кода на peewee-async где не работает данный функционал:

import asyncio
from peewee import *
from peewee_async import *
db = PooledMySQLDatabase(...)

class BaseModel(AioModel):
    class Meta:
        database = db

class Favorite(AioModel):
    text = TextField()

class Tweet(AioModel):
    user_id = IntegerField()
    name = TextField()
    favorite = ForeignKeyField(Favorite, backref='favorites')

db.create_tables([
    Favorite,
    Tweet
])

db.set_allow_sync(False)

async def main():
    info_favorite = await Favorite.aio_create(text="text uwu")
    await Tweet.aio_create(user_id=11, favorite=info_favorite, name="Durov")

    info = await Tweet.aio_get(user_id=11)
    print(info.name) # work
    print(info.favorite.text) # error
    >     
    assert self._allow_sync, (
           ^^^^^^^^^^^^^^^^
    AssertionError: Error, sync query is not allowed! Call the `.set_allow_sync()` or use the `.allow_sync()` context manager.

asyncio.run(main())

Maybe I'm doing something wrong, I don't exclude this option

@kalombos
Copy link
Collaborator

Асинхронного варианта для ForeignKeyField на данный моент нет. А если его добавлять, то нужно будет обязательно добавлять ключевое слово await:

text = (await info.favorite).text

Скорей всего это приведет к тому, что все будут забывать добавлять await и будут получать ошибку "У корутины нет аттрибута text". На мой взгляд лучше использовать join-ы, либо можно самому написать запрос

favorite = await Favorite.aio_get(Favorite.id==info.favorite_id)
print(favorite.text)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants