question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Returning fields computed/derived from values of other fields

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

class MyModel(BaseModel):

    a: str
    b: str

    @property
    def c():
        return a + b

Description

I’m trying to make FastAPI return some extra fields as part of my JSON response which is based on the values of some other fields.

I can’t find any mention of this in the docs.

I don’t want to add the derived field and mutate the object whenever its dependencies update, as that seems a lot more error prone. Ideally I’d love to do something like in the example code snippet, where c is defined to always be a + b and this gets evaluated whenever a response is serialised.

Thanks!

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.63.0

Python Version

3.8.7

Additional Context

No response

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
Norbo11commented, Jan 14, 2022

@dylanwa indeed, I’m using root_validator and it’s working quite well:

from abc import abstractmethod

from pydantic import BaseModel, root_validator


class BaseModelWithStringRepresentation(BaseModel):

    string_representation: str = ""

    @classmethod
    @abstractmethod
    def get_string_representation(cls, values: dict):
        pass

    @root_validator
    def validate_string_representation(cls, values: dict):
        values["string_representation"] = cls.get_string_representation(values)
        return values

I have models subclassing BaseModelWithStringRepresentation and implementing get_string_representation where they will return a value based on some computation on their fields. Thanks @kaiix for the suggestion.

0reactions
ericman93commented, Apr 10, 2022

what is the best solution for adding calculated fields from the DB? I have output model and it’s dict method I added fetches to return to the user but dict is sync method and my db queries can be async

Read more comments on GitHub >

github_iconTop Results From Across the Web

Computed fields - Prisma
Computed fields allow you to derive a new field based on existing data. A common example is when you compute a full name...
Read more >
Computed Fields - IBM
Computed fields bring the ability to define fields on an object whose value is computed from the values of other fields. These other...
Read more >
Dynamic/Virtual field values using computed field property ...
Sometimes it is necessary to have "computed" properties in a field, alongside actual values that are stored in the database.
Read more >
Create a field whose value is a calculation of other fields' values
Nor does this help if the value is something that it resource-intensive to compute, and you only want to do it when other...
Read more >
Formulas vs other computed fields - Airtable Support
These can be fields that allow you to compute a value based on values in other fields (like formula, lookup, count, and rollup)...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found