Volbil
Just use python datetime library
Vitaliy
AttributeError: 'datetime' object has no attribute 'timestamp': s.updated.timestamp and TypeError: unsupported callable when doing like datetime.fromtimestamp(s.status['updated'])
Volbil
No need to convert it using fromtimestamp
Vitaliy
s.updated is not converted, I call .timestamp() to compare it with the value stored in Json field s.status (s.status['updated'] is int timestamp)
Kyle
Hello
Kyle
@metaprogrammer when addind a new record from a entity is there a way to ignore keys from dict that doesn't exists on the entity?
Kyle
TypeError: Unknown attribute 'xxxx'
Matthew
you can get the columns from an entity with _cols_ or cols or something like that
Matthew
then filter with a dict comprehension
Lucas
can some1 help me with this query in pony?
Lucas
what I want is, order mangas by latest chapters
Alexander
I think you can use any of: left_join(m for m in Manga for c in m.chapters).order_by(lambda: desc(max(c.created_at))) Manga.select().order_by(lambda m: desc(max(m.chapters.created_at))) The first query uses explicit left_join. Note that lambda used without arguments, so c inside lambda appears to be taken from the outer scope, it may be highlighted as an error in PyCharm. The reason is, if lambda in order_by receives an argument, it is interpreted as the result of select. In this query, the result of select is m, so in order_by(lambda x: ...) the x values will be logically the same as m values. Lambda without any named argument has a specific meaning, it allows to access any iterator variable by name even if it is not yielded as a result of select. So, in lambda: c the value of c is logically the same value as for c variable inside select iterator loop. The max aggregation function in the first query has SQL semantics, and looks like SQL max function. In the second query Manga.select().order_by(lambda m: desc(max(m.chapters.created_at))) Pony understands that it is theoretically possible to have Manga object with zero chapters, and Python semantics of iteration expects that this Manga object will still appear in the result list, so Pony automatically changes select to left_join here. m.chapters.created_at is an example of attribute lifting. m.chapters is a collection of chapters, and in Pony each collection has all attributes of its items, which values are multisets. So, this m.chapters collection has created_at attribute, which value is another collection, a multiset of all created_at values of m.chapters items. In this second query max function receives not a single attribute value, but a collection, and in this case max has Python semantics. The second query Manga.select().order_by(lambda m: desc(max(m.chapters.created_at))) can also be expressed without attribute lifting as Manga.select().order_by(lambda m: desc(max(c.created_at for c in m.chapters))) But this third query, while return the same result, translates differently. In the second query, Pony understands, that, while collection m.chapters.created_at conceptually should be presented as a subquery, it is possible to optimize the query and replace subquery with LEFT JOIN and GROUP BY In the third query, max(c.created_at for c in m.chapters) looks more complex to Pony and Pony cannot automatically replace it with LEFT JOIN, so Pony will use real subquery inside ORDER BY, and it may be less efficient
Lucas
very nice, thank you for ur explanation.
Genesis Shards Community
buenos dias, estoy queriendo realizar una suma con un filtro, pero suma todos los registro totalenvios = sum(e.importe for e in Envio if e.idagencia.idagencia == _idagencia and e.fecha >= dateMonthStart and e.fecha <= dateMonthEnd)
Genesis Shards Community
como puedo hacer que me sume solo los registros que cumplen las condiciones
Genesis Shards Community
helpme please!
Alexander
Hi, can you formulate your question in English?
Genesis Shards Community
select sum(e.importe) from envio as e where e.idagencia.idagencia = _idagencia and e.fecha >= dateMonthStart and e.fecha <= dateMonthEnd
Genesis Shards Community
its in ponyorm
Alexander
The code that you provided for the query looks correctly totalenvios = sum( e.importe for e in Envio if e.idagencia.idagencia == _idagencia and e.fecha >= dateMonthStart and e.fecha <= dateMonthEnd ) Does it generate wrong SQL?
Alexander
You can exec sql_debug(True) and compare generated SQL with SQL that you wrote above
Genesis Shards Community
why?
Alexander
I'm not sure I understand your question correctly
El Mojo
como puedo hacer que me sume solo los registros que cumplen las condiciones
En la documentación hay muchos ejemplos para hacer lo que quieras 🙂
Sergey
Hello. Tell me how to upload and download a pdf file from the database via pony? To create a pdf, I use the fpdf library.
Aleksey
Entity User and Site located in different modules. User has attribute sites = Set('Site'). I have error: pony.orm.core.ERDiagramError: Entity definition Site was not found. How to fix it?
Matthew
Use “bytes” as your field type to store binary data
D
Hi ! Excuse me for being rude, but are there any news about migrations in pony orm? Should we expect 'em soon, or use diy solutions
Alexander
Hi! At this moment it is better to use something like Flyway for migrations
D
Thanks for a fast reply, gonna see it
El Mojo
Hi guys! What about async? Should we expect it soon? Sorry for insisting 🙂
D
One more question please. Say I have an Entity with a nested Entity (e.g. set Photo - tags of type Tag). I want to serialize the Photo object, and be able to view full tag infomation (not just ids). .to_dict(with_collections=True, related_objects=True) shows empty dictionaries instead of tag dictionary. Have I missed anything?
D
https://gist.github.com/Kamori/2b574057e9f514732e9c9296136d7929
Alexander
Hi guys! What about async? Should we expect it soon? Sorry for insisting 🙂
We don't plan to release async support soon, but in a few days I'll start refactoring some async code that uses Pony to "separate thread with queue" approach, and if the result will be successful, I'll think how to apply it to Pony itself
Lucky
Uh, that's great news!
Alexander
found good workaround for this, should I request this as feature?
I'm not sure this approach is flexible enough to be included in Pony itself. But I agree there is a need to something better than to_dict
Lucky
I still think including support for pydantic would be a great idea, maybe that could do the json lifting as well?
Alexander
I agree that adding support for Pydantic would be great
Kyle
I've an async app running and that need constant db access and fast response times. I've tried using tortoise orm but it's just not fast as pony, pony is 10x faster for my case, I'm just using tortoise for logging rn. I use some thread pools for slower queries, having that integrated would be good if we can get access to the thread object to await it
Kyle
Is it possible to share your experience with thread pools and pony?
Hey sure, it's nothing fancy tho... For functions with slower db operation I run them with loop.run_in_executor(pool, func) which is awaitable, pool being a concurrent.futures.ThreadPoolExecutor
Kyle
App do that at client login part where it needs to load all client data that can't be cached because there are multiple servers
zip
hi folks, when declaring a new Entity that has a relationship to another Entity... how do i map the relationship when instantiating? I have Users and Feature Entities... i instantiated a User successfully doing: bob = User(name="Bob") but when i instantiate a Feature like: bobs_feature = Feature(user=bob) i get the following error: TransactionError: An attempt to mix objects belonging to different transactions
zip
this seems to work: bobs_feature = Feature(user=User[1]) but the documentation states i should be able to use an instance of bob
Volbil
this seems to work: bobs_feature = Feature(user=User[1]) but the documentation states i should be able to use an instance of bob
If I understood you correctly, you should be able to query User, store it inside variable and pass it as an argument when creating bew instance of Feature
zip
If I understood you correctly, you should be able to query User, store it inside variable and pass it as an argument when creating bew instance of Feature
yes, i was able to do eventually.. just not in sequential lines... i had to requery for my User before making a Feature
Volbil
Something wrong with this approach?
zip
im not able to instantiate a User and Feature inside a single 'with db_session':
zip
no, i was just unaware of how to do it... first time ive used pony with relationships
zip
is it possible to have pony orm add new columns (class attributes) to an existing table?
Volbil
is it possible to have pony orm add new columns (class attributes) to an existing table?
It requires db schema migration which could be painful experience
zip
It requires db schema migration which could be painful experience
yes, and i see that codebase hasnt been updated in years.
zip
im switching to peewee :D
Anonymous
hello will ponyorm be async
zip
You mean Pony?
the migrations pieces
Volbil
Ah
Volbil
I see
zip
toodles
Anonymous
Alexander
@metaprogrammer
Hi, eventually we'll add async features to Pony, but not in the near future probably. In a few days, I will refactor some async application code to use it with Pony in an efficient way, maybe I will get some useful insights from this process.
Alexander
im not able to instantiate a User and Feature inside a single 'with db_session':
You should be able to do it db = Database('sqlite', ':memory:') class Student(db.Entity): id = PrimaryKey(int) name = Required(str) group = Optional("Group") class Group(db.Entity): number = PrimaryKey(str) students = Set("Student") db.generate_mapping(create_tables=True) with db_session: s1 = Student(id=1, name="John") s2 = Student(id=2, name="Bob") g1 = Group(number="G101", students=[s1, s2]) g2 = Group(number="G102") s3 = Student(id=3, name="Mike", group=g2) g2.students += Student(id=4, name="Mary") g2.students.create(id=5, name="Alex") > i get the following error: > TransactionError: An attempt to mix objects belonging to different transactions That means that you created objects in a different db_sessions
El Mojo
is it possible to have pony orm add new columns (class attributes) to an existing table?
Used dbmate along with pony, quite easy to "implement " migrations
El Mojo
Do you have an example?
Nothing fancy, I write sql for each new modification 🙂 and then use dbmate migrate to keep track of migrations
Volbil
Ah, I see
Matthew
Merry Christmas all. I'm trying to do this: "a.last_retry < datetime.datetime.now() - datetime.timedelta(minutes=5 * a.retries_count)" - but getting a not implemented error. Would I need to store a timedelta in the database, or there is a way to get something like my query to work?
Anonymous
Hi there, yesterday I played around with custom methods in entities. In the docs I saw some examples, but only for instances. What about mentioning class methods for methods which are used for general purposes? Example: @classmethod def active_user_count(cls): return cls.select(lambda a: a.active is True).count() This allows you to use this method like this: >>> print(User.active_user_acount()) 10 Regards, Thomas
Anonymous
I usually do service class for this purpose
Another good idea! Thx. My purpose was to leave those methods inside the entity where they belong to. It's a bit like MongoEngines queryset_manager.
John Doe
Hi all! I wrote backend rest - fastapi - pony app on python 3.8 and i got exceptions in this block of code - TypeError: Entity instance or a sequence of instances expected. Got: <pony.orm.core.QueryResultIterator object at 0x10560e150>
John Doe
please help me