nazrulworld / fhir.resources

FHIR Resources https://www.hl7.org/fhir/resourcelist.html
https://pypi.org/project/fhir.resources/
Other
365 stars 104 forks source link

Is it possible to disable the validation? #99

Closed Minitour closed 2 years ago

Minitour commented 2 years ago

This is more of a general question rather than an issue. I am wondering if it is possible to disable the validation all together or at least make it passive such that the instantiated objects only hold the fields that did pass the validation.

For example I might have an encounter resource that has one of the mandatory fields missing. Instead of raising an error I would like to create an object with whatever fields do exist.

Is there a workaround to achieve this?

blazing-gig commented 2 years ago

@Minitour I've been using this library for a while now. I had a slightly different use-case where I had to defer validation until all fields (including mandatory ones) were populated by parsing some configuration. I found that by default Config.validate_assignment is True in the base class and so validation automatically kicks in upon attribute assignment.

There are two ways to circumvent the problem:

  1. Create a subclass that overrides the Config.validate_assignment attribute to False. This will disable validation until triggered manually.
    
    from fhir.resources.encounter import Encounter as _Encounter

class FhirResource(BaseModel): class Config: validate_assignment = False

class Encounter(FhirResource, _Encounter): ...

e = Encounter.construct() # -> skips validation while instantiation e.id = "something" # -> doesn't trigger validation



2. Iterate over all classes available in the library (fhirtypesvalidators.py) and call `get_fhir_model_class` and dynamically set `model_cls.__config__.validate_assignment` to `False`. 

I'd recommend the first approach as it's declarative and explicit. However, if there are just too many classes for which you want this behaviour and subclassing manually seems cumbersome, then the second approach will work provided the code responsible for patching executes before importing any of the classes. (Typically the entrypoint of your script/framework from where the import chain starts.) 
Minitour commented 2 years ago

Okay, I will try this out, thanks for the detailed comment!

Minitour commented 2 years ago

I ended up using this code and it seems to do the trick

from fhir.resources.fhirtypesvalidators import MODEL_CLASSES, get_fhir_model_class

# Disable the FHIR validation
for key in MODEL_CLASSES.keys():
    model = get_fhir_model_class(key)
    model.__config__.validate_assignment = False