Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

computed_field properties not showing in tables #320

Closed
jimkring opened this issue May 26, 2024 · 4 comments · Fixed by #321
Closed

computed_field properties not showing in tables #320

jimkring opened this issue May 26, 2024 · 4 comments · Fixed by #321

Comments

@jimkring
Copy link
Contributor

I have a model with some computed_fields and they do not show up automatically when I try to render them in a table, unless I explicitly define the columns of the table (and reference the field by name with a DisplayLookup).

The problem/inconvenience with this, is that now I have to specify every column with a DisplayLookup, just to include the one column that is a computed property. This makes my code less DRY and harder to maintain.

it would be nice if the table logic would find these computed properties and include them when the columns/fields are discovered.

@hasansezertasan
Copy link
Contributor

I believe the main problem is here at the DisplayLookup builder logic:

if self.columns is None:
self.columns = [
display.DisplayLookup(field=name, title=field.title)
for name, field in data_model_type.model_fields.items()
]
else:
# add pydantic titles to columns that don't have them
for column in (c for c in self.columns if c.title is None):
field = data_model_type.model_fields.get(column.field)
if field and field.title:
column.title = field.title
return self

Computed fields are accessible by model.model_computed_fields.items(), check this out:

from pydantic import BaseModel, computed_field


class Rectangle(BaseModel):
    width: int
    length: int

    @computed_field
    @property
    def area(self) -> int:
        return self.width * self.length


data = Rectangle(width=3, length=4)
data.model_fields.items() # Model Fields
data.model_computed_fields.items() # Computed Fields

@hasansezertasan
Copy link
Contributor

I'll work on this tomorrow and try to come up with a proper solution 🤓.

@jimkring
Copy link
Contributor Author

@hasansezertasan thank you for the good insights and for looking into this enhancement!

@hasansezertasan
Copy link
Contributor

@hasansezertasan thank you for the good insights and for looking into this enhancement!

You're welcome, I'm happy to be able to work on this issue 🤓.

I'd like to have your review if you got time to spare. #321

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants