Skip to content

What is the best way to create a read-only/allow_mutation=False field? #110

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

Open
jidn opened this issue Oct 5, 2021 · 5 comments
Open
Labels
enhancement New feature or request question Further information is requested

Comments

@jidn
Copy link

jidn commented Oct 5, 2021

Similar to the id field, I have a created_on field the database will auto create for me. Now, what is the best way to not allow the field in POST, PUT but have it in GETs?

  1. Require the use of Create and Update Schema. Nothing would need to change, but all that schema creation smells of boilerplate.
  2. Modify the _utils.py schema_factory to allow for additional fields to exclude. However, at that point you might as well add id to that list and make it generic.
  3. Modify the _utils.py schema_factory to look for allow_mutation and exclude it along with id.
for f in schema_cls.__fields__.values()
if f.name != pk_field_name and f.field_info.allow_mutation

Now my field could look something like

# Not in OpenAPI post or put
update_on: datetime.datetime = Field(
    allow_mutation=False, description="Last update from sync system"
)

Is there a better way to remove fields from Create and Update schemas easily?

@awtkns
Copy link
Owner

awtkns commented Oct 5, 2021

Hi @jidn thanks for bringing this up.

I totally agree with what you suggested. I think removing fields with allow_mutation=false in the schema factory would be a great way of reducing potential boiler plate. 🚀

Is this something you would be interested in PRing?

@awtkns awtkns added enhancement New feature or request question Further information is requested labels Oct 5, 2021
@jidn
Copy link
Author

jidn commented Oct 5, 2021

Sure. Any tips where to best insert tests?

jidn pushed a commit to jidn/fastapi-crudrouter that referenced this issue Oct 6, 2021
schema_factory currently ignores the primary field 'id'.
This allows any field annotated with allow_mutation=False the same ability.
@jidn
Copy link
Author

jidn commented Oct 18, 2021

Is there anything else you need for this patch?

@awtkns
Copy link
Owner

awtkns commented Oct 18, 2021

Hey thanks for the reminder @jidn. I am planning on merging this in the coming days (with the next release).

@jsenecal
Copy link

Hey @awtkns , Do you know when this is going to be part of a released version ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants