I want to add a derived field that is calculated from an expression referencing other fields. I didn’t see any explanation of this in the documentation on Field types. Is it possible?
BillJ
June 2, 2022, 7:47pm
2
Virtual fields are on their way in V14:
frappe:develop
← gavindsouza:dynamic-docfields
opened 09:22AM - 27 Oct 21 UTC
### Virtual DocFields
Consider adding a property to your DocType controller, … like age to Person as shown below
```python
class Person(Document):
@property
def age(self):
return frappe.utils.now_datetime() - self.creation
```
Before this, _age_ would show up as `None`. But, through this, the value is set nicely when accessed via `as_dict` / REST.
If you have a `@property` in the controller class, this data used to not be accessible anywhere other than directly through the object via `frappe.get_doc`.
<img width="1440" alt="Screenshot 2021-10-27 at 12 05 25 PM" src="https://user-images.githubusercontent.com/36654812/139035135-8157c96f-b00f-4716-82aa-e0c3b7932415.png">
I added a read-only Data **virtual** field to Note, called it difference and added the following block in the Note controller.
```python
@property
def difference(self):
return self.modified - self.creation
```
<img width="1440" alt="Screenshot 2021-10-27 at 12 05 08 PM" src="https://user-images.githubusercontent.com/36654812/139035108-5e3732e1-51de-452e-8c45-235c6d6e3a3c.png">
Made changes to raise via `check_fieldname_conflicts` to ignore virtual fields. Although, a msgprint will be shown as a nudge/reminder.
ref: https://github.com/frappe/frappe/issues/14462#issuecomment-952576498
> This PR introduces a Virtual check for DocFields, similar to DocTypes.
Docs: https://frappeframework.com/docs/v13/user/en/basics/virtual_docfield
There was some discussion on how to custom-code it in earlier versions here but I don’t know if anyone got it to work:
Is there a way to have a kind of virtual field on a doctype, evaluated at the time of usage
For example I am triggering a webhook which needs a bearer token calculated and populated as one of the headers
if it is possible I want to use jinja template in the headers with that evaluated value