@escript decorator and magic methods 🔮
Magic @escript decorator¶
@escript decorator is a method-decorator, that is used for decorating methods of "epurized" (1) class
- "epurized" class is class that was decorated by
@epure()decorator
@escript decorator magicly convert your queries into strings
Info
Only in method decorated by @escript, can be used instances of self.dom, self.md and method self.model
Lets see an example:
Alien Cats example 👽🐈¶
Retrieving cats with more than one tail using @escript
For example you have a class Cat:
-
with more than one tail (lets assume there are some cat-alien species 👽)
-
and those cats who don't like catnip (a real weird cat-aliens)
Then we will define a method
for
class Cat decorated by @escript:
...
@classmethod
@escript
def get_all_cats_with_two_tails(cat):
my_query = cat.md.tail_cntr > 1 and cat.md.likes_catnip == False
res = cat.resource.read(my_query)
res # [<Cat object at 0x000001FFFC6800D0>, <Cat object at 0x000001FCFC6800D7>, ...]
...
Let's look closely to my_query:
First, because method is a classmethod, in cat variable will be assigned class.Then we are taking .md Model of Cat class and taking Column tail_cntr and comparing it to more than 1
In resulting list we will get cats with more than one tail and those who doesnt like catnip. Like expected!
All avalible for self.md methods
All the avalible methods (e.g. ==, like, is_not, _is etc), for self.md can be found in Column Proxy methods section
More Advanced Alien Cats 👽🐈 example with for¶
So if we want to create something more complex, lets use for statement:
Creating advanced smart query with for
So as in previous example you have a class Cat:
But this time you want to get Cat(s) that:
- has a tail (i.e
tail_cntris not `#!sql NULL``) - has a name and name starts with letter
'C' - has less than 5 paws or equally 8 paws (more like an octocat )
- likes catnip 🍀
So we will define magic
method for
Cat class:
True at the same time.
But what do we do? 🤔
Create a long-long query, that is unreadable and to much hassle to edit? Nah ❌.
I suggest to use for loop ✔️.
This way, we can put them in a list and iterate over it adding and to each condition, sticking it all together
line 18 result_query = has_tail_query explanation
This assignemnt made mainly made because we need to start somewhere and we cant use empty string ("") as a start.
This way we will get a long smart query without any hassle and code confusion.