<commit_before>from cornflake.sqlalchemy_orm import ModelSerializer, ReferenceField
from cornflake import fields
from cornflake.validators import none_if_blank, optional, max_length, min_, required
from cornflake.exceptions import ValidationError

from radar.api.serializers.common import (
    PatientMixin,
    MetaMixin,
    SourceMixin,
    StringLookupField
)
from radar.api.serializers.validators import valid_date_for_patient
from radar.models.medications import Medication, Drug, MEDICATION_DOSE_UNITS, MEDICATION_ROUTES


class ParentDrugSerializer(ModelSerializer):
    class Meta(object):
        model_class = Drug
        exclude = ['parent_drug_id']


class ParentDrugField(ReferenceField):
    model_class = Drug
    serializer_class = ParentDrugSerializer


class DrugSerializer(ModelSerializer):
    parent_drug = ParentDrugField()

    class Meta(object):
        model_class = Drug
        exclude = ['parent_drug_id']


class DrugField(ReferenceField):
    model_class = Drug
    serializer = DrugSerializer


class MedicationSerializer(PatientMixin, SourceMixin, MetaMixin, ModelSerializer):
    from_date = fields.DateField()
    to_date = fields.DateField(required=False)
    drug = DrugField(required=False)
    dose_quantity = fields.FloatField(required=False, validators=[min_(0)])
    dose_unit = StringLookupField(MEDICATION_DOSE_UNITS, required=False)
    frequency = fields.StringField(required=False, validators=[none_if_blank(), optional(), max_length(1000)])
    route = StringLookupField(MEDICATION_ROUTES, required=False)
    drug_text = fields.StringField(required=False, validators=[none_if_blank(), optional(), max_length(10000)])
    dose_text = fields.StringField(required=False, validators=[none_if_blank(), optional(), max_length(10000)])

    class Meta(object):
        model_class = Medication
        exclude = ['drug_id']
        validators = [
            valid_date_for_patient('from_date'),
            valid_date_for_patient('to_date'),
        ]

    def pre_validate(self, data):
        # Coded drug overrides drug free-text
        if data['drug']:
            data['drug_text'] = None

        return data

    def validate(self, data):
        data = super(MedicationSerializer, self).validate(data)

        if data['to_date'] is not None and data['to_date'] < data['from_date']:
            raise ValidationError({'to_date': 'Must be on or after from date.'})

        if data['drug'] is None and data['drug_text'] is None:
            raise ValidationError({
                'drug': 'Must specify a drug.',
                'drug_text': 'Must specify a drug.',
            })

        if data['dose_quantity'] is not None:
            self.run_validators_on_field(data, 'dose_unit', [required()])

        return data
<commit_msg>Fix drugs not being serialized<commit_after>from cornflake.sqlalchemy_orm import ModelSerializer, ReferenceField
from cornflake import fields
from cornflake.validators import none_if_blank, optional, max_length, min_, required
from cornflake.exceptions import ValidationError

from radar.api.serializers.common import (
    PatientMixin,
    MetaMixin,
    SourceMixin,
    StringLookupField
)
from radar.api.serializers.validators import valid_date_for_patient
from radar.models.medications import Medication, Drug, MEDICATION_DOSE_UNITS, MEDICATION_ROUTES


class ParentDrugSerializer(ModelSerializer):
    class Meta(object):
        model_class = Drug
        exclude = ['parent_drug_id']


class ParentDrugField(ReferenceField):
    model_class = Drug
    serializer_class = ParentDrugSerializer


class DrugSerializer(ModelSerializer):
    parent_drug = ParentDrugField()

    class Meta(object):
        model_class = Drug
        exclude = ['parent_drug_id']


class DrugField(ReferenceField):
    model_class = Drug
    serializer_class = DrugSerializer


class MedicationSerializer(PatientMixin, SourceMixin, MetaMixin, ModelSerializer):
    from_date = fields.DateField()
    to_date = fields.DateField(required=False)
    drug = DrugField(required=False)
    dose_quantity = fields.FloatField(required=False, validators=[min_(0)])
    dose_unit = StringLookupField(MEDICATION_DOSE_UNITS, required=False)
    frequency = fields.StringField(required=False, validators=[none_if_blank(), optional(), max_length(1000)])
    route = StringLookupField(MEDICATION_ROUTES, required=False)
    drug_text = fields.StringField(required=False, validators=[none_if_blank(), optional(), max_length(10000)])
    dose_text = fields.StringField(required=False, validators=[none_if_blank(), optional(), max_length(10000)])

    class Meta(object):
        model_class = Medication
        exclude = ['drug_id']
        validators = [
            valid_date_for_patient('from_date'),
            valid_date_for_patient('to_date'),
        ]

    def pre_validate(self, data):
        # Coded drug overrides drug free-text
        if data['drug']:
            data['drug_text'] = None

        return data

    def validate(self, data):
        data = super(MedicationSerializer, self).validate(data)

        if data['to_date'] is not None and data['to_date'] < data['from_date']:
            raise ValidationError({'to_date': 'Must be on or after from date.'})

        if data['drug'] is None and data['drug_text'] is None:
            raise ValidationError({
                'drug': 'Must specify a drug.',
                'drug_text': 'Must specify a drug.',
            })

        if data['dose_quantity'] is not None:
            self.run_validators_on_field(data, 'dose_unit', [required()])

        return data

{'fraction_non_alphanumeric': 0.09676843420817711, 'fraction_numerical': 0.005356186395286556, 'mean_word_length': 3.73541842772612, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2747572', 'n_tokens_mistral': 1663, 'n_tokens_neox': 1564, 'n_words': 364}