From 77bb19c9624cd53268015988b75473cbf89abcb0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabor=20K=C3=B6rber?= Date: Wed, 2 Jun 2021 10:50:33 +0200 Subject: [PATCH] updating readme --- blackmesa/records/readme.md | 48 ++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/blackmesa/records/readme.md b/blackmesa/records/readme.md index b491a1f..de34958 100644 --- a/blackmesa/records/readme.md +++ b/blackmesa/records/readme.md @@ -2,8 +2,13 @@ Create arbitrary classes instead of django models for usage in layered architectures. +## Index -## Records fetching Data directly into Dataclasses + - Records fetching Data into arbitrary classes + - Deeper Example + - TODO: setting up your models and querysets + +## Records fetching Data into arbitrary classes ##### The records() QuerySet and Manager command @@ -64,3 +69,44 @@ Just as with expressions, you can of course also write your own Adjunct classes, If records() is not provided a class or handler, you can define a default either on the Manager or QuerySet, by using `_default_record`. You can also put this on the model class. If a record class is not found, an Exception is raised. +## Deeper Example + +Assume we have a model like so in models.py (made simpler to read by leaving out details): + +```python +class MyModel: + name = models.CharField() + age = models.IntegerField() + parent = models.ForeignKey('self') + data = models.TextField() + + objects = records.RecordManager() +``` + +Now let's assume we have a dataclass in domain.py: + +```python +@dataclass +class MyRecord: + name: str + age: int + parent_id: int + parent_name: str + has_data: bool +``` + +Building this record, which for now we assume will be a frozen dataclass in the future, would be done like this: + +```python +MyModel.objects.filter(...).records(MyRecord, 'data', age=Adjunct(0), parent_name=F('parent__name'), has_data=Lambda(lambda d: d.get('data') is not None)) +``` + +This will return an iterator that will contain data like this: `[MyRecord(name=..., age=0, parent_id=..., parent_name=..., has_data=...), ...]` + +What has been done here? + - the field data was not on MyRecord, but needed by has_data, so it was included in the values() call by providing it as a string argument. + - name will be automatically inserted. the parent_id will be picked up as well, containing the primary key of the parent. They do not need to be defined in the records() call. + - age however will always be 0, and not inserted into the db call. + - the parent_name was, just like in values(), a Django Expression as kwarg. it will be written into the appropriate field. + - has_data finally will get it's data by calling the lambda function for each fetch, when the record is instantiated. for that it will extract whether the data entry returned some value from the db, which we included earlier for this reason. Of course this would have been possible with a db call as well, but this is to show the mechanic. +