pythonpydantichl7-fhirhapi-fhirdstu2-fhir

How to extend a fhir class?


I want to append some relevant data to FHIR lets say patient or condition object for further processing. I tried to extend the FHIR patient class in python. Getting the following error. Could somebody give me some helpful pointers here? Thanks!

import fhir.resources.patient as pt

patient = pt.Patient.parse_file('patient.json')


class Patient2(pt.Patient):
    def __init__(self,validDia):
        self.validDia=validDia


newPatient = Patient2(1)
print(newPatient)


---------------------
  File "pydantic\main.py", line 357, in pydantic.main.BaseModel.__setattr__
ValueError: "Patient2" object has no field "validDia" ```

Solution

  • If you want to extend your model you have to use Pydantic models.

    For patient.json file i used data from fhir dock

    Code example:

    import json
    import fhir.resources.patient as pt
    
    
    class Patient2(pt.Patient):
        validDia: int
    
    
    with open("patient.json", "r") as file:
        json_obj = json.load(file)
    
    
    json_obj.update({"validDia": 1})
    
    
    newPatient = Patient2.parse_obj(json_obj)
    print(newPatient)
    print(newPatient.validDia)
    

    And the output:

    >>> resource_type='Patient' fhir_comments=None id='p001' ...cut out... validDia=1
    >>> 1