class SatisfactionRating(models.EpisodeSubrecord): _is_singleton = True SATISFACTION_CHOICES = ( ('Dissatisfied', 'Dissatisfied',), ('Satisfied', 'Satisfied',), ('Very Satisfied', 'Very Satisfied',), ) labor_analgesia = fields.CharField( choices=SATISFACTION_CHOICES, blank=True, null=True, max_length=255, ) delivery_analgesia = fields.CharField( choices=SATISFACTION_CHOICES, blank=True, null=True, max_length=255, ) post_natal_analgesia = fields.CharField( choices=SATISFACTION_CHOICES, blank=True, null=True, max_length=255, )
class Structure(Model): name = fields.CharField(max_length=50, blank=True, null=True) address = models.ForeignKey(Address, blank=True, null=True) description = fields.CharField(max_length=250, blank=True, null=True) total_seats = fields.IntegerField(blank=True, null=True) available_seats = fields.IntegerField(blank=True, null=True) active = fields.BooleanField(default=True) owner = models.ForeignKey(Volunteer, blank=True, null=True) def update_availability(self): occupied_sits = 0 for evacuee in self.evacuees.all(): occupied_sits += evacuee.group_size self.available_seats = self.total_seats - occupied_sits self.save() def notify_assignation(self, evacuee): if self.owner.user and evacuee.user: Notification.objects.create( time=datetime.now(), kind='assignation', message='Struttura "{}" assegnata a "{} {}"'.format( self.name, evacuee.name, evacuee.surname), user=self.owner.user) Notification.objects.create( time=datetime.now(), kind='assignation', message='Assegnata struttura "{}" da "{} {}"'.format( self.name, self.owner.name, self.owner.surname), user=evacuee.user)
class Clerking(models.EpisodeSubrecord): _icon = 'fa fa-user' _title = 'Seen by' referrer = fields.CharField(max_length=200, blank=True, null=True) clerked_by = fields.CharField(max_length=200, blank=True, null=True) consultant = fields.CharField(max_length=200, blank=True, null=True)
class OperationNote(models.EpisodeSubrecord): start_time = fields.TimeField() end_time = fields.TimeField() date = fields.DateField() lead_surgeon = models.ForeignKeyOrFreeText( StaffMember, related_name="%(class)s_lead_surgeon") lead_anaesthetist = models.ForeignKeyOrFreeText( StaffMember, related_name="%(class)s_lead_anaesthetist") surgeon = ManyToManyField(StaffMember, related_name="%(class)s_surgeon") assistant = ManyToManyField(StaffMember, related_name="%(class)s_assistant") anaesthetist = ManyToManyField(StaffMember, related_name="%(class)s_anaesthetist") dvt_heparin = fields.BooleanField(default=False) dvt_ted_stockings = fields.BooleanField(default=False) dvt_pnematic = fields.BooleanField(default=False) dvt_aspirin = fields.BooleanField(default=False) antibiotics = fields.CharField(max_length=40) indication = fields.CharField(max_length=20) position = fields.CharField(max_length=20) incision = fields.CharField(max_length=20) findings = fields.TextField() procedure = fields.TextField() anaesthetic = models.ForeignKeyOrFreeText(AnaestheticType) cancer = models.ForeignKeyOrFreeText(CancerType) asa = models.ForeignKeyOrFreeText(AsaType) urgency = models.ForeignKeyOrFreeText(Urgency)
class OAuthClient(models.Model): """ Model to manage OAuth API of content source providers. Content source API connections. """ AUTH_CODE = "authorization code" IMPLICIT = "implicit" PASSWORD = "******" CREDENTIALS = "client credentials" GRANT_TYPES = ( ('code', AUTH_CODE), ('implicit', IMPLICIT), ('password', PASSWORD), ('credentials', CREDENTIALS), ) name = fields.CharField(max_length=255, blank=True, null=True, unique=True) client_id = models.CharField(max_length=255) client_secret = models.CharField(max_length=255) grant_type = fields.CharField( choices=GRANT_TYPES, default='credentials', max_length=255, null=True, blank=True, help_text='OAuth grant type which is used by OpenEdx API.') class Meta: verbose_name = "OAuth Client" verbose_name_plural = "OAuth Clients" def __str__(self): return '<OAuthClient: {}>'.format(self.name or self.client_id)
class DebtLoan(models.Model): DEBT = 0 LOAN = 1 CATEGORY_CHOICES = ( (DEBT, 'debt'), (LOAN, 'loan'), ) with_who = fields.CharField(max_length=255) title = fields.CharField(max_length=255, null=True, blank=True) amount = fields.DecimalField(max_digits=10, decimal_places=2) category = fields.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) created = fields.DateTimeField(default=timezone.now, editable=False) modified = fields.DateTimeField(default=timezone.now) active = fields.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): if self.title: return "{}: {}".format(self.with_who, self.title) else: return "{}".format(self.with_who) def deactivate(self): if self.active: self.active = False self.save()
class Account(Model): identifier = fields.CharField(max_length=1000) type = fields.CharField(choices=ACCOUNT_TYPE_LIST, max_length=len(max(ACCOUNT_TYPE_LIST, key=len))) balance_offset = fields.IntegerField(default=0) @property def current_balance(self): from .transaction import Transaction return round(self.balance_offset + Transaction.objects .filter(account=self) .aggregate(total_value=aggregates.Sum('value'))['total_value'], 2) def get_balance(self, start_date): from .transaction import Transaction if start_date.month+1 > 12: end_date = dt.date(year=start_date.year+1, month=1, day=5) else: end_date = dt.date(year=start_date.year, month=start_date.month + 1, day=5) total = Transaction.objects\ .filter(account=self, date__gte=start_date, date__lt=end_date)\ .aggregate(total_value=aggregates.Sum('value'))['total_value'] if total is None: total = 0 return round(total, 2) class Meta: unique_together = (('identifier', 'type'), ) def __str__(self): return '{type} account: {identifier}'.format(type=self.type, identifier=self.identifier)
class AnimalCard(models.Model): name = f.CharField(max_length=20, verbose_name='Имя') animal = models.ForeignKey(Animal, on_delete=models.PROTECT, verbose_name='Животное') breed = f.CharField(max_length=15, blank=True, verbose_name='Порода') gender = f.CharField(max_length=7, choices=GENDER_CHOICES, verbose_name='Пол') age = f.CharField(max_length=15, blank=True, verbose_name='Возраст') state_time_admission = f.CharField( max_length=18, choices=ANIMAL_CONDITION_CHOICES, verbose_name='Состояние на момент приема') reason_getting_shelter = f.TextField(verbose_name='Причина приема') additional_inform = f.TextField(blank=True, verbose_name='Дополнительная информация') date_receipt = f.DateTimeField(auto_now_add=True, verbose_name='Дата приема') # photo = f.ImageField() is_adopted = f.BooleanField(blank=True, default=False, verbose_name='Усыновлен ли') def __str__(self): return self.name
class Leg(models.Model): date = fields.DateField(default=now) name = fields.CharField(max_length=40, unique=True) slug = fields.SlugField(max_length=40, db_index=True, editable=False) start = fields.CharField(max_length=30) end = fields.CharField(max_length=30) description = fields.TextField(max_length=320, blank=True) duration = fields.DecimalField(decimal_places=1, max_digits=2, default=1.0) distanceKM = fields.IntegerField() morning = fields.BooleanField(default=True) map = models.FileField(upload_to=get_map_path, blank=True) class Meta: unique_together = ('date', 'morning') def __str__(self): return "{} - {} {}: {}km from {} to {}".format( self.name, self.date, "am" if self.morning else "pm", self.distanceKM, self.start, self.end) @classmethod def Totals(cls): return cls.objects.aggregate(distance=Sum('distanceKM'), days=Count('date', distinct=True)) prepopulated_fields = {"slug": ("title", )}
class Evacuee(Model): name = fields.CharField(max_length=50, blank=True, null=True) surname = fields.CharField(max_length=50, blank=True, null=True) fiscal_code = fields.CharField(max_length=20, blank=True, null=True) category = fields.CharField(max_length=20, blank=True, null=True) note = fields.CharField(max_length=200, blank=True, null=True) address = models.ForeignKey(Address, blank=True, null=True) user = models.ForeignKey(User, related_name='evacuee_profile', blank=True, null=True) assigned_structure = models.ForeignKey(Structure, related_name='evacuees', blank=True, null=True) assigned_time = fields.DateTimeField(blank=True, null=True) @property def is_assigned(self): return self.assigned_structure is not None @property def group_size(self): return 1 + self.group.count() def assign_structure(self, structure): self.assigned_structure = structure self.assigned_time = datetime.now() self.save() structure.update_availability() structure.notify_assignation(self)
class Currency(models.Model): id = fields.AutoField( verbose_name=_('ID'), primary_key=True, ) iso_code = fields.CharField( verbose_name=_('ISO Code'), max_length=3, null=False, blank=False, unique=True, ) title = fields.CharField( verbose_name=_('Title'), max_length=255, null=False, blank=False, ) prefix = fields.CharField( verbose_name=_('Prefix'), max_length=255, null=False, blank=True, ) suffix = fields.CharField( verbose_name=_('Suffix'), max_length=255, null=False, blank=True, ) rate = fields.DecimalField( verbose_name=_('Conversion Rate'), max_digits=10, decimal_places=4, null=False, blank=False, default=1, ) is_active = fields.BooleanField( verbose_name=_('Is Active'), null=False, blank=False, default=True, db_index=True, ) records = models.Manager() class Meta: db_table = 'billing_currency' default_related_name = 'currencies' verbose_name = _('Currency') verbose_name_plural = _('Currencies') def __unicode__(self): return '%(id)d: %(title)s (%(iso_code)s)' % { 'id': self.id, 'iso_code': self.iso_code, 'title': self.title, }
class SmokingHistory(models.EpisodeSubrecord): _title = 'Smoking History' ever_smoked = fields.NullBooleanField() current_smoker = fields.NullBooleanField() start_smoking_age = fields.CharField(max_length=20, blank=True, null=True) stop_smoking_age = fields.CharField(max_length=20, blank=True, null=True) cigarettes_per_day = fields.CharField(max_length=20, blank=True, null=True) what_do_you_smoke = fields.TextField(blank=True, null=True)
class SocCode(models.models.Model): soc90 = fields.CharField(max_length=200) soc2000 = fields.CharField(max_length=200) title = fields.CharField(max_length=255) short_desc = fields.TextField() entry = fields.TextField() tasks = fields.TextField() related = fields.TextField()
class WinPathResult(models.EpisodeSubrecord): _read_only = True _sort = 'profile_code' lab_number = fields.CharField(max_length=200, blank=True, null=True) visible_in_list = fields.BooleanField(default=False) profile_code = fields.CharField(max_length=200, blank=True, null=True) profile_description = fields.CharField(max_length=200, blank=True, null=True) request_datetime = fields.DateTimeField(blank=True, null=True) observation_datetime = fields.DateTimeField(blank=True, null=True) last_edited = fields.DateTimeField(blank=True, null=True) result_status = fields.CharField(max_length=200, blank=True, null=True) observations = fields.TextField(blank=True, null=True) @classmethod def create_or_update_from_gloss(klass, identifier, data): lab_number = data['lab_number'] print 'lab number', lab_number print 'identifier', identifier # First, check if we have this lab number... if klass.objects.filter(lab_number=lab_number).count() > 0: result = klass.objects.get(lab_number=lab_number) episode = result.episode patient = episode.patient else: patient = models.Patient.objects.first() # patient = models.Patient.objects.all()[1] if patient.episode_set.count() == 0: episode = patient.create_episode() episode.active = True episode.save() else: episode = patient.episode_set.first() result = klass(episode=episode, lab_number=lab_number) def date_from_key(prop): return make_aware( datetime.datetime.strptime(data[prop], '%Y/%m/%d %H:%M')) result.profile_code = data['profile_code'] result.profile_description = data['profile_description'] result.request_datetime = date_from_key('request_datetime') result.observation_datetime = date_from_key('observation_datetime') result.last_edited = date_from_key('last_edited') result.result_status = data.get('result_status', None) result.observations = data['observations'] result.save() return def to_dict(self, user): d = super(WinPathResult, self).to_dict(user) d['observations'] = json.loads(self.observations) return d
class Choice(models.Model): name = fields.CharField(max_length=200) key = fields.CharField(max_length=200, unique=True) description = fields.TextField(default='', blank=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) image_url = fields.URLField(blank=True, null=True) def __str__(self): return self.name
class Log(models.Model): """ Student actions log. Every time student opens/submits lti problem new Log created. """ OPENED = 'O' SUBMITTED = 'S' ADMIN = 'A' LOG_TYPES = ( (OPENED, 'Opened'), (SUBMITTED, 'Submitted'), (ADMIN, 'Admin'), ) ACTIVITY_CREATED = 'AC' ACTIVITY_UPDATED = 'AU' ACTIVITY_DELETED = 'AD' COLLECTION_CREATED = 'CC' COLLECTION_UPDATED = 'CU' ACTIONS = ( (ACTIVITY_CREATED, 'Activity created'), (ACTIVITY_UPDATED, 'Activity updated'), (ACTIVITY_DELETED, 'Activity deleted'), (COLLECTION_CREATED, 'Collection created'), (COLLECTION_UPDATED, 'Collection updated'), ) sequence_item = models.ForeignKey('SequenceItem', null=True, blank=True, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, blank=True, null=True) log_type = fields.CharField(choices=LOG_TYPES, max_length=32) answer = models.BooleanField(verbose_name='Is answer correct?', default=False) attempt = models.PositiveIntegerField(default=0) action = fields.CharField(choices=ACTIONS, max_length=2, null=True, blank=True) data = JSONField(default={}, blank=True) def __str__(self): if self.log_type == self.OPENED: return '<Log[{}]: {}>'.format(self.get_log_type_display(), self.sequence_item) elif self.log_type == self.ADMIN: return '<Log[{}]: {} ({})>'.format(self.get_log_type_display(), self.get_action_display(), self.data) else: return '<Log[{}]: {}-{}[{}]>'.format(self.get_log_type_display(), self.sequence_item, self.answer, self.attempt)
class OccupationalHistory(models.PatientSubrecord): _title = "Occupational History" job_name = fields.CharField(max_length=250, blank=True, null=True) job_tasks = fields.TextField(blank=True, null=True) employer_output = fields.CharField( max_length=250, blank=True, null=True) # change label to be what did you make start_year = fields.CharField(max_length=4, blank=True, null=True) end_year = fields.CharField(max_length=4, blank=True, null=True) address = fields.TextField(blank=True, null=True)
class Volunteer(Model): name = fields.CharField(max_length=50, blank=True, null=True) surname = fields.CharField(max_length=50, blank=True, null=True) fiscal_code = fields.CharField(max_length=20, blank=True, null=True) note = fields.CharField(max_length=200, blank=True, null=True) address = models.ForeignKey(Address, blank=True, null=True) user = models.ForeignKey(User, related_name='volunteer_profile', blank=True, null=True)
class OccupationalHistory(models.PatientSubrecord): _title = "Occupational History" job_name = fields.CharField(max_length=250, blank=True, null=True) soc_job = models.ForeignKeyOrFreeText(SocJob, verbose_name="Job name") job_tasks = fields.TextField(blank=True, null=True) employer_output = fields.CharField( max_length=250, blank=True, null=True) # change label to be what did you make start_year = fields.CharField(max_length=4, blank=True, null=True) end_year = fields.CharField(max_length=4, blank=True, null=True) address = fields.TextField(blank=True, null=True)
class SimpleEvacuee(Model): name = fields.CharField(max_length=50, blank=True, null=True) surname = fields.CharField(max_length=50, blank=True, null=True) fiscal_code = fields.CharField(max_length=20, blank=True, null=True) category = fields.CharField(max_length=20, blank=True, null=True) note = fields.CharField(max_length=200, blank=True, null=True) leader = models.ForeignKey(Evacuee, related_name='group', blank=True, null=True) address = models.ForeignKey(Address, blank=True, null=True)
class Collection(HasLinkedSequenceMixin, models.Model): """Set of Activities (problems) for a module.""" name = fields.CharField(max_length=255) slug = AutoSlugField( populate_from='name', unique=True, db_index=True, help_text= "Add the slug for the collection. If field empty slug will be created automatically.", verbose_name='slug id') owner = models.ForeignKey(BridgeUser, on_delete=models.CASCADE) metadata = fields.CharField(max_length=255, blank=True, null=True) strict_forward = fields.BooleanField(default=True) updated_at = fields.DateTimeField(auto_now=True) class Meta: unique_together = ('owner', 'name') def __str__(self): return '<Collection: {}>'.format(self.name) def save(self, *args, **kwargs): """Extension cover method with logging.""" initial_id = self.id super().save(*args, **kwargs) tasks.sync_collection_engines.apply_async( kwargs={ 'collection_slug': self.slug, 'created_at': self.updated_at }, countdown=settings.CELERY_DELAY_SYNC_TASK, ) if initial_id: Log.objects.create(log_type=Log.ADMIN, action=Log.COLLECTION_UPDATED, data={'collection_id': self.id}) else: Log.objects.create(log_type=Log.ADMIN, action=Log.COLLECTION_CREATED, data={'collection_id': self.id}) def get_absolute_url(self): return reverse('module:collection-list') def get_launch_url(self, group): return "{}{}".format( settings.BRIDGE_HOST, reverse("lti:launch", kwargs={ 'collection_slug': self.slug, 'group_slug': group.slug }))
class UserProfile(ModelBase): first_name = fields.CharField(max_length=127) last_name = fields.CharField(max_length=127, null=True, blank=True) phone = fields.CharField(max_length=20) class Meta: indexes = [ models.Index(fields=[ 'first_name', 'last_name', ]), ]
class EpiduralInsertion(models.EpisodeSubrecord): insertion_date_time = fields.DateTimeField( null=True, # default=timezone.now, (causes an Opal APIerror if uncommented) help_text= "Date and time of the epidural insertion or epidural insertion attempt", ) # TODO should ideally allow SNOMED codes to be embedded in the text insertion_record = fields.TextField( null=True, max_length=255, help_text="Free text clinical record of the intervention", ) # TODO should ideally be SNOMEDized indication = fields.CharField( null=True, max_length=255, help_text="Description of the intervention", ) number_of_attempts = fields.PositiveIntegerField( default=1, help_text="The number of discrete epidural insertion attempts", ) # TODO should ideally be SNOMEDized # TODO consider a default value? "no immediate complications" complications = fields.CharField( blank=True, null=True, max_length=255, help_text="Complications caused by the epidural insertion", ) # TODO should ideally be SNOMEDized # TODO any other options @TimCKnowles? OUTCOME_CHOICES = ( ("SUCCESS", "Successful epidural insertion and effective analgesia"), ("INEFFECTIVE", "Successful insertion of epidural catheter"), ("DURAL PUNCTURE", "Epidural insertion caused dural puncture"), ("FAILURE", "Failed epidural insertion"), ) outcome = fields.CharField( choices=OUTCOME_CHOICES, blank=True, null=True, help_text="Outcome of the epidural insertion attempt", max_length=255, )
class Task(ModelBase): STATUS_LIST = [('DONE', 'DONE'), ('NOTDONE', 'NOTDONE'), ('DELETED', 'DELETED')] owner = models.ForeignKey(User) name = fields.CharField(max_length=127) status = fields.CharField(max_length=127, choices=STATUS_LIST, default=STATUS_LIST[1][0]) description = fields.TextField(null=True, blank=True) def __unicode__(self): return self.name
class Fp17DentalCareProvider(models.PatientSubrecord): _is_singleton = True _title = "Provider details" # I'm pretty sure this should not be handled as a PatientSubrecord # but I'm not sure what it /should/ be # the following provider information is not currently in an Opal model # ^^^ consider splitting this into a Provider Model provider_name = fields.CharField(max_length=255, blank=True, null=True) provider_location_number = fields.CharField(max_length=255, blank=True, null=True) provider_address = fields.CharField(max_length=255, blank=True, null=True) performer_number = fields.CharField(max_length=255, blank=True, null=True)
class Country(models.Model): id = fields.AutoField( verbose_name=_('ID'), primary_key=True, ) iso_code = fields.CharField( verbose_name=_('ISO Code'), max_length=2, null=False, blank=False, unique=True, ) title = fields.CharField( verbose_name=_('Title'), max_length=255, null=False, blank=False, ) default_language = models.ForeignKey( Language, related_name='countries', null=True, blank=True, ) default_currency = models.ForeignKey( Currency, related_name='countries', null=True, blank=True, ) is_active = fields.BooleanField( verbose_name=_('Is Active'), null=False, blank=False, default=True, db_index=True, ) records = models.Manager() class Meta: db_table = 'billing_country' default_related_name = 'countries' verbose_name = _('Country') verbose_name_plural = _('Countries') def __unicode__(self): return '%(id)d: %(title)s (%(iso_code)s)' % { 'id': self.id, 'iso_code': self.iso_code, 'title': self.title, }
class UserProfile(models.Model): """Model for github user data """ username = fields.CharField(max_length=512, unique=True) image_url = fields.URLField(null=True, blank=True) name = fields.CharField(null=True, max_length=127) company = fields.CharField(null=True, max_length=127) email = fields.CharField(null=True, max_length=127) adding_date = fields.DateTimeField(auto_now_add=True) class Meta: verbose_name = "GitHub User" def __unicode__(self): return "{}".format(self.username)
class Registration(Model): camp = ForeignKey(Camp, on_delete=CASCADE) clan = ForeignKey(Clan, on_delete=PROTECT) telephone = fields.CharField(max_length=100) contact_name = fields.CharField(max_length=100) email = fields.EmailField(max_length=100) comment = fields.TextField(max_length=1000, null=True, blank=True) paid = fields.DecimalField(decimal_places=2, max_digits=6, default=0) rules_accepted = fields.BooleanField(default=False, validators=[validate_true]) present_participants = fields.PositiveIntegerField(null=True) def get_price(self): price = 0 for info in self.ticketinfo_set.all(): price += info.quantity * info.fee.price return price def get_quantity(self): quantity = 0 for info in self.ticketinfo_set.all(): quantity += info.quantity return quantity def get_quantities(self): quantities = list() for fee in self.camp.fee_set.all().order_by('pk'): value = 0 for info in self.ticketinfo_set.all(): if info.fee == fee: value = info.quantity quantities.append(value) return quantities def get_ticket_count(self): tickets = list() for info in self.ticketinfo_set.all(): tickets.extend(info.ticket_set.all()) return len(tickets) def get_registrated_participant_count(self): count = 0 for info in self.ticketinfo_set.all(): for ticket in info.ticket_set.all(): if ticket.registrated: count += 1 return count def __str__(self): return "Registration from {}".format(self.clan.name)
class Node(APIUser): foreign_username = fields.CharField(max_length=32) foreign_pass = fields.CharField(max_length=32) outbound = fields.BooleanField(default=False) image_sharing = fields.BooleanField(default=True) # Used to set parent "type" to "Node" def __init__(self, *args, **kwargs): for f in self._meta.fields: if f.attname == "type": f.default = "Node" super(Node, self).__init__(*args, **kwargs) def __unicode__(self): return u'%s:%s' % (self.id, self.host)
class ParentCard(models.Model): fio = f.CharField(max_length=100, verbose_name='ФИО') address = f.CharField(max_length=100, verbose_name='Адрес') phone_number = PhoneNumberField(null=False, unique=True, verbose_name='Номер телефона') gender = f.CharField(max_length=7, choices=GENDER_CHOICES, verbose_name='Пол') date_of_birth = f.DateTimeField(verbose_name='Дата рождения', blank=True, null=True) email = f.EmailField(verbose_name='E-mail') def __str__(self): return self.fio