1 |
|
2 .. _FetchAttrs: |
|
3 |
|
4 Loaded attributes and default sorting management |
|
5 ```````````````````````````````````````````````` |
|
6 |
|
7 * The class attribute `fetch_attrs` allows to define in an entity class a list |
|
8 of names of attributes or relations that should be automatically loaded when |
|
9 entities of this type are fetched from the database. In the case of relations, |
|
10 we are limited to *subject of cardinality `?` or `1`* relations. |
|
11 |
|
12 * The class method `fetch_order(attr, var)` expects an attribute (or relation) |
|
13 name as a parameter and a variable name, and it should return a string |
|
14 to use in the requirement `ORDERBY` of an RQL query to automatically |
|
15 sort the list of entities of such type according to this attribute, or |
|
16 `None` if we do not want to sort on the attribute given in the parameter. |
|
17 By default, the entities are sorted according to their creation date. |
|
18 |
|
19 * The class method `fetch_unrelated_order(attr, var)` is similar to |
|
20 the method `fetch_order` except that it is essentially used to |
|
21 control the sorting of drop-down lists enabling relations creation |
|
22 in the editing view of an entity. The default implementation uses |
|
23 the modification date. Here's how to adapt it for one entity (sort |
|
24 on the name attribute): :: |
|
25 |
|
26 class MyEntity(AnyEntity): |
|
27 __regid__ = 'MyEntity' |
|
28 fetch_attrs = ('modification_date', 'name') |
|
29 |
|
30 @classmethod |
|
31 def fetch_unrelated_order(cls, attr, var): |
|
32 if attr == 'name': |
|
33 return '%s ASC' % var |
|
34 return None |
|
35 |
|
36 |
|
37 The function `fetch_config(fetchattrs, mainattr=None)` simplifies the |
|
38 definition of the attributes to load and the sorting by returning a |
|
39 list of attributes to pre-load (considering automatically the |
|
40 attributes of `AnyEntity`) and a sorting function based on the main |
|
41 attribute (the second parameter if specified, otherwise the first |
|
42 attribute from the list `fetchattrs`). This function is defined in |
|
43 `cubicweb.entities`. |
|
44 |
|
45 For example: :: |
|
46 |
|
47 class Transition(AnyEntity): |
|
48 """...""" |
|
49 __regid__ = 'Transition' |
|
50 fetch_attrs, fetch_order = fetch_config(['name']) |
|
51 |
|
52 Indicates that for the entity type "Transition", you have to pre-load |
|
53 the attribute `name` and sort by default on this attribute. |
|