caps.utils
- get_lazy_relation(obj, field, out_field=None)[source]
For the provided model instance, return an attribute name and value for field.
It returns relation id if the relation hasn’t been fetched from the db. Otherwise, it returns the relation object:
access = Access.objects.all().first() # relation has not been fetched k, v = get_lazy_relation(access, 'origin') assert k == 'origin_id' and isinstance(v, int) # fetch from db: access.origin k, v = get_lazy_relation(access, 'origin') assert k == 'origin' and isinstance(v, Access) # map a name: k, v = get_lazy_relation(access, 'origin', 'dest') assert k == 'dest' and isinstance(v, Access)
- Parameters:
obj – object to get value on
field – object’s field to lookup
out_field (
str|None) – output field (default to object’s)
- Return type:
tuple[str,Any]
:return a tuple with field name and value.
caps.utils.nested
- class NestedBase(name, bases, attrs)[source]
Bases:
objectThis metaclass allows to create nested class based from parent one.
By default, the method will first look for an existing declaration. If none is found it will create one with only the declared
nested_classas base. This means that you must manually declare any other parent class:class Nested: pass class ParentBase(NestedBase): nested_class = Nested @classmethod def create_nested_class(cls, name, attrs={}): return super(Parent, cls).create_nested_class( name, {"custom_field": ForeignKey()} ) class Parent(metaclass=NestedBase): pass class A(Parent): # you must declare its bases class Nested(Nested): # customize code here pass class C(A, B): # you need to be explicit class Nested(A.Nested): pass
- classmethod create_nested_class(new_class, name, attrs={})[source]
Create the nested class for the provided container one to-be-created.
- Parameters:
new_class (
type[object]) – the parent class that just has been createdname (
str) – nested class nameattrs (
dict[str,Any]) – nested class attributes
- Return type:
type
:return the newly created class.
- classmethod get_nested_class(new_class)[source]
Get nested model class or creates a new one.
- Parameters:
new_class (type[object])
-
nested_class:
type[object] = None Nested class base to create.
-
nested_name:
str|None= None Attribute and class name of the nested class. If not provided, takes it from
nested_class
-
new_name:
str= '{class_name}{nested_name}' Name format for newly created classes.