Пример #1
0
class Association(models.Model):
    research = models.ForeignKey('KB_Exp.Research')
    tumor = models.ForeignKey('KB_Exp.Tumor')
    gene = models.ForeignKey('KB_Exp.Gene')
    prognosis = models.ForeignKey('KB_Exp.Prognosis')
    subgroup = models.ForeignKey('KB_Exp.Subgroup', null=True, blank=True)
    expression = models.CharField(max_length=50)
    case_number = models.IntegerField(null=True, blank=True)
    control_number = models.IntegerField(null=True, blank=True)
    total_number = models.IntegerField(null=True, blank=True)
    or_u = models.FloatField(null=True, blank=True)
    hr_u = models.FloatField(null=True, blank=True)
    rr_u = models.FloatField(null=True, blank=True)
    ci_u_95 = FloatRangeField(null=True, blank=True)
    p_u = models.CharField(max_length=50, null=True, blank=True)
    or_m = models.FloatField(null=True, blank=True)
    hr_m = models.FloatField(null=True, blank=True)
    rr_m = models.FloatField(null=True, blank=True)
    ci_m_95 = FloatRangeField(null=True, blank=True)
    p_m = models.CharField(max_length=50, null=True, blank=True)

    def __str__(self):
        return "No.{} [{!s}][{}]{}".format(self.pk, self.tumor,
                                           self.gene.gene_official_symbol,
                                           self.expression)
Пример #2
0
class PostgresModel(Model):
    int_array = ArrayField(IntegerField(null=True, blank=True),
                           size=3,
                           null=True,
                           blank=True)

    hstore = HStoreField(null=True, blank=True)
    try:
        from django.contrib.postgres.fields import JSONField
        json = JSONField(null=True, blank=True)
    except ImportError:
        pass

    int_range = IntegerRangeField(null=True, blank=True)
    try:
        from django.contrib.postgres.fields import FloatRangeField
        float_range = FloatRangeField(null=True, blank=True)
    except ImportError:
        pass

    try:
        from django.contrib.postgres.fields import DecimalRangeField
        decimal_range = DecimalRangeField(null=True, blank=True)
    except ImportError:
        pass
    date_range = DateRangeField(null=True, blank=True)
    datetime_range = DateTimeRangeField(null=True, blank=True)

    class Meta:
        # Tests schema name in table name.
        db_table = '"public"."cachalot_postgresmodel"'
Пример #3
0
class TestRecordFieldFloatRangeValue(models.Model):
    rang_or_not = models.BooleanField()
    value = FloatRangeField()
    test_record_field = models.ForeignKey(
        TestRecordField,
        related_name='test_field_float_result',
        on_delete=models.PROTECT)
Пример #4
0
    class PostgresModel(Model):
        int_array = ArrayField(IntegerField(null=True, blank=True),
                               size=3,
                               null=True,
                               blank=True)

        hstore = HStoreField(null=True, blank=True)

        int_range = IntegerRangeField(null=True, blank=True)
        float_range = FloatRangeField(null=True, blank=True)
        date_range = DateRangeField(null=True, blank=True)
        datetime_range = DateTimeRangeField(null=True, blank=True)
Пример #5
0
class RangeAttribute(models.Model):
    """Атрибут товара диапазонный"""
    product = models.ForeignKey(Product, models.CASCADE, verbose_name='товар')
    filter = models.ForeignKey(RangeFilter, models.CASCADE, verbose_name='атрибут')
    values = FloatRangeField('диапазон значений', blank=True, null=True)

    def __str__(self):
        return str(self.filter.name)

    class Meta:
        verbose_name = 'атрибут-диапазон'
        verbose_name_plural = 'атрибуты-диапазон'
        unique_together = (('product', 'filter'),)
Пример #6
0
class AuditTableLog(ReadOnlyModel):

    relid = models.IntegerField(primary_key=True)
    schema_name = models.TextField()
    table_name = models.TextField()
    txid_range = FloatRangeField()

    class Meta:
        managed = False
        db_table = 'audit_table_log'
        app_label = 'pg_memento'

    def __str__(self):
        return str(self.table_name)
Пример #7
0
class Association(models.Model):
    research = models.ForeignKey('KB_SNP.Research')
    tumor = models.ForeignKey('KB_SNP.Tumor')
    variant = models.ForeignKey('KB_SNP.Variant')
    prognosis = models.ForeignKey('KB_SNP.Prognosis')
    subgroup = models.ForeignKey('KB_SNP.Subgroup', null=True, blank=True)
    genotype = models.CharField(max_length=50)
    case_number = models.IntegerField(null=True, blank=True)
    control_number = models.IntegerField(null=True, blank=True)
    total_number = models.IntegerField(null=True, blank=True)
    or_u = models.FloatField(null=True, blank=True)
    hr_u = models.FloatField(null=True, blank=True)
    rr_u = models.FloatField(null=True, blank=True)
    ci_u_95 = FloatRangeField(null=True, blank=True)
    p_u = models.CharField(max_length=50, null=True, blank=True)
    or_m = models.FloatField(null=True, blank=True)
    hr_m = models.FloatField(null=True, blank=True)
    rr_m = models.FloatField(null=True, blank=True)
    ci_m_95 = FloatRangeField(null=True, blank=True)
    p_m = models.CharField(max_length=50, null=True, blank=True)

    def __str__(self):
        return "[{!s}][{}][{}]{}".format(self.tumor, self.variant.gene.gene_official_symbol,
                                         self.variant.dbsnp, self.genotype)
Пример #8
0
class PostgresModel(Model):
    int_array = ArrayField(IntegerField(null=True, blank=True), size=3,
                           null=True, blank=True)

    hstore = HStoreField(null=True, blank=True)

    json = JSONField(null=True, blank=True)

    int_range = IntegerRangeField(null=True, blank=True)
    float_range = FloatRangeField(null=True, blank=True)
    date_range = DateRangeField(null=True, blank=True)
    datetime_range = DateTimeRangeField(null=True, blank=True)

    class Meta:
        # Tests schema name in table name.
        db_table = '"public"."cachalot_postgresmodel"'
Пример #9
0
class Image_Style(models.Model):
    image = models.ForeignKey('Image', on_delete=models.CASCADE)
    width = models.IntegerField(blank=True, default=0)
    width_range = IntegerRangeField(
        default='(1, 101)',
        blank=True,
        validators=[RangeMinValueValidator(1),
                    RangeMaxValueValidator(100)])
    height = models.IntegerField(blank=True, default=0)
    height_range = IntegerRangeField(
        default='(1,101)',
        blank=True,
        validators=[RangeMinValueValidator(1),
                    RangeMaxValueValidator(100)])
    brads_tl = models.IntegerField(blank=True, default=0)
    brads_tl_range = IntegerRangeField(
        default='(1,101)',
        blank=True,
        validators=[RangeMinValueValidator(1),
                    RangeMaxValueValidator(100)])
    brads_tr = models.IntegerField(blank=True, default=0)
    brads_tr_range = IntegerRangeField(
        default='(1,101)',
        blank=True,
        validators=[RangeMinValueValidator(1),
                    RangeMaxValueValidator(100)])
    brads_bl = models.IntegerField(blank=True, default=0)
    brads_bl_range = IntegerRangeField(
        default='(1,101)',
        blank=True,
        validators=[RangeMinValueValidator(1),
                    RangeMaxValueValidator(100)])
    brads_br = models.IntegerField(blank=True, default=0),
    brads_br_range = IntegerRangeField(
        default='(1,101)',
        blank=True,
        validators=[RangeMinValueValidator(1),
                    RangeMaxValueValidator(100)])
    opacity = models.FloatField(blank=True, default=1)
    opacity_range = FloatRangeField(
        default='(0.1, 1.1)',
        blank=True,
        validators=[RangeMinValueValidator(0.1),
                    RangeMaxValueValidator(1.1)])
    marquee = models.BooleanField(
        default=False
    )  #should look this up...? maybe set up a function to do so.and automatically tie it to the IRS.
Пример #10
0
class Research(models.Model):
    title = models.CharField(max_length=500, unique=True)
    language = models.CharField(max_length=50)
    pub_year = models.IntegerField()
    pubmed_id = models.IntegerField(null=True, blank=True)
    url = models.URLField(max_length=500)
    pub_type = models.CharField(max_length=50)
    ebml = models.ForeignKey('KB_SNP.EvidenceBasedMedicineLevel')
    ethnicity = models.CharField(max_length=100, null=True, blank=True)
    patient_number = models.IntegerField(null=True, blank=True)
    male = models.IntegerField(null=True, blank=True)
    female = models.IntegerField(null=True, blank=True)
    median_age = models.FloatField(null=True, blank=True)
    mean_age = models.FloatField(null=True, blank=True)
    age_range = FloatRangeField(null=True, blank=True)
    treatment_desc = models.TextField(null=True, blank=True)
    treatment_type = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return "{}".format(self.title)
Пример #11
0
class AuditColumnLog(ReadOnlyModel):

    table_relid = models.ForeignKey('AuditTableLog', db_column='table_relid')
    column_name = models.TextField()
    ordinal_position = models.IntegerField()
    column_default = models.TextField()
    is_nullable = models.CharField(max_length=3)
    data_type = models.TextField()
    data_type_name = models.TextField()
    char_max_length = models.IntegerField()
    numeric_precision = models.IntegerField()
    numeric_precision_radix = models.IntegerField()
    numeric_scale = models.IntegerField()
    datetime_precision = models.IntegerField()
    interval_type = models.TextField()
    txid_range = FloatRangeField()

    class Meta:
        managed = False
        db_table = 'audit_column_log'
        app_label = 'pg_memento'

    def __str__(self):
        return str(self.id)
Пример #12
0
class Migration(migrations.Migration):

    dependencies = [
        ('auth', '0001_initial'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Test',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=20)),
                ('public', models.BooleanField(default=False)),
                ('date', models.DateField(null=True, blank=True)),
                ('datetime', models.DateTimeField(null=True, blank=True)),
                ('owner', models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL)),
                ('permission', models.ForeignKey(blank=True, to='auth.Permission', null=True, on_delete=models.PROTECT)),
                ('a_float', models.FloatField(null=True, blank=True)),
                ('a_decimal', models.DecimalField(null=True, blank=True, max_digits=5, decimal_places=2)),
                ('bin', models.BinaryField(null=True, blank=True)),
                ('ip', models.GenericIPAddressField(null=True, blank=True)),
                ('duration', models.DurationField(null=True, blank=True)),
                ('uuid', models.UUIDField(null=True, blank=True)),
            ],
            options={
                'ordering': ('name',),
            },
        ),
        migrations.CreateModel(
            name='TestParent',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=20)),
            ],
        ),
        migrations.CreateModel(
            name='TestChild',
            fields=[
                ('testparent_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cachalot.TestParent', on_delete=models.CASCADE)),
                ('public', models.BooleanField(default=False)),
                ('permissions', models.ManyToManyField('auth.Permission', blank=True))
            ],
            bases=('cachalot.testparent',),
        ),
        HStoreExtension(),
        UnaccentExtension(),
        migrations.CreateModel(
            name='PostgresModel',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False,
                                        auto_created=True, primary_key=True)),
                ('int_array', ArrayField(
                    models.IntegerField(null=True, blank=True), size=3,
                    null=True, blank=True)),
                ('hstore', HStoreField(null=True, blank=True)),
                ('json', JSONField(null=True, blank=True)),
                ('int_range', IntegerRangeField(null=True, blank=True)),
                ('float_range', FloatRangeField(null=True, blank=True)),
                ('date_range', DateRangeField(null=True, blank=True)),
                ('datetime_range', DateTimeRangeField(null=True, blank=True)),
            ],
        ),
    ]
Пример #13
0
    Migration.operations.extend((
        migrations.AddField('Test', 'duration',
                            models.DurationField(null=True, blank=True)),
        migrations.AddField('Test', 'uuid',
                            models.UUIDField(null=True, blank=True)),
        migrations.RunSQL('CREATE EXTENSION hstore;',
                          hints={'extension': 'hstore'}),
        migrations.RunSQL('CREATE EXTENSION unaccent;',
                          hints={'extension': 'unaccent'}),
        migrations.CreateModel(
            name='PostgresModel',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('int_array',
                 ArrayField(models.IntegerField(null=True, blank=True),
                            size=3,
                            null=True,
                            blank=True)),
                ('hstore', HStoreField(null=True, blank=True)),
                ('int_range', IntegerRangeField(null=True, blank=True)),
                ('float_range', FloatRangeField(null=True, blank=True)),
                ('date_range', DateRangeField(null=True, blank=True)),
                ('datetime_range', DateTimeRangeField(null=True, blank=True)),
            ],
        ),
    ))
Пример #14
0
class Bat(models.Model):
    """
    Describes a model that has all the traits for a bat.

    This is consumed on the front-end to show species of bats to the user,
    as well as a way to tag what bats were seen at a particular House.
    """
    common_name = models.CharField(max_length=255,
                                   help_text="Name used in everyday life")
    scientific_name = models.CharField(
        max_length=255, help_text="Formal system used for naming species")

    RARITY_CHOICES = (('CO', 'Common'), ('SC', 'Seasonally Common'), ('RA',
                                                                      'Rare'))
    rarity = models.CharField(max_length=2,
                              choices=RARITY_CHOICES,
                              default='CO',
                              help_text="How often the species is seen")

    HABIT_CHOICES = (('HI', 'Hibernates'), ('MI', 'Migrates'),
                     ('CR', 'Cave roosts'), ('TR', 'Tree roosts'))
    habits = ChoiceArrayField(
        models.CharField(max_length=2, choices=HABIT_CHOICES),
        blank=True,
        help_text="What the species tends to do in order to survive")

    size = FloatRangeField(help_text="Typical size in inches")
    pups = IntegerRangeField(help_text="Typical offspring per year")

    RISK_CHOICES = (('NT', 'Not threatened'), ('EN', 'Endangered'),
                    ('TH', 'Threatened'), ('SC', 'Special concern'))
    risk = ChoiceArrayField(models.CharField(max_length=2,
                                             choices=RISK_CHOICES),
                            blank=True,
                            help_text="Conservation status for the species")

    SCOPE_CHOICES = (('ST', 'State'), ('FE', 'Federally'))
    risk_scope = ChoiceArrayField(
        models.CharField(max_length=2, choices=SCOPE_CHOICES, null=True),
        blank=True,
        null=True,
        help_text="Whether or not this applies at the federal or state level")

    bat_image = models.ForeignKey(
        'wagtailimages.Image',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

    panels = [
        MultiFieldPanel([
            FieldPanel('common_name', classname="col12"),
            FieldPanel('scientific_name', classname="col12"),
        ],
                        heading="Identification",
                        classname="collapsible"),
        MultiFieldPanel([
            FieldPanel('rarity', classname="col12"),
            FieldPanel('habits',
                       classname="col12",
                       widget=forms.CheckboxSelectMultiple),
            FieldPanel('risk',
                       classname="col12",
                       widget=forms.CheckboxSelectMultiple),
            FieldPanel('risk_scope',
                       classname="col12",
                       widget=forms.CheckboxSelectMultiple),
        ],
                        heading="Information",
                        classname="collapsible"),
        MultiFieldPanel([
            FieldRowPanel([
                FieldPanel('size', classname="col6"),
                FieldPanel('pups', classname="col6"),
            ])
        ],
                        heading="Characteristics",
                        classname="collapsible"),
        ImageChooserPanel('bat_image')
    ]

    def __str__(self):
        return f"{self.common_name} ({self.scientific_name})"
Пример #15
0
class TestFieldValidFloatRange(models.Model):
    rang_or_not = models.BooleanField()
    value = FloatRangeField()
    test_field = models.ForeignKey(TestField,
                                   related_name='test_field_valid_float_range',
                                   on_delete=models.PROTECT)
Пример #16
0
class Award(TimeStampedModel):
    """
    Award Model.

    The specific award conferred by a Group.
    """

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )

    name = models.CharField(
        help_text="""Award Name.""",
        max_length=255,
    )

    STATUS = Choices(
        (-10, 'inactive', 'Inactive',),
        (0, 'new', 'New',),
        (10, 'active', 'Active',),
    )

    status = FSMIntegerField(
        help_text="""DO NOT CHANGE MANUALLY unless correcting a mistake.  Use the buttons to change state.""",
        choices=STATUS,
        default=STATUS.new,
    )

    KIND = Choices(
        (32, 'chorus', "Chorus"),
        (41, 'quartet', "Quartet"),
    )

    kind = models.IntegerField(
        choices=KIND,
    )

    GENDER = Choices(
        (10, 'male', "Male"),
        (20, 'female', "Female"),
        (30, 'mixed', "Mixed"),
    )

    gender = models.IntegerField(
        help_text="""
            The gender to which the award is restricted.  If unselected, this award is open to all combinations.
        """,
        choices=GENDER,
        null=True,
        blank=True,
    )

    LEVEL = Choices(
        (10, 'championship', "Championship"),
        (30, 'qualifier', "Qualifier"),
        (45, 'representative', "Representative"),
        (50, 'deferred', "Deferred"),
        (60, 'manual', "Manual"),
        (70, 'raw', "Improved - Raw"),
        (80, 'standard', "Improved - Standard"),
    )

    level = models.IntegerField(
        choices=LEVEL,
    )

    SEASON = Choices(
        (1, 'summer', 'Summer',),
        (2, 'midwinter', 'Midwinter',),
        (3, 'fall', 'Fall',),
        (4, 'spring', 'Spring',),
    )

    season = models.IntegerField(
        choices=SEASON,
    )

    is_single = models.BooleanField(
        help_text="""Single-round award""",
        default=False,
    )

    threshold = models.FloatField(
        help_text="""
            The score threshold for automatic qualification (if any.)
        """,
        null=True,
        blank=True,
    )

    minimum = models.FloatField(
        help_text="""
            The minimum score required for qualification (if any.)
        """,
        null=True,
        blank=True,
    )

    advance = models.FloatField(
        help_text="""
            The score threshold to advance to next round (if any) in
            multi-round qualification.
        """,
        null=True,
        blank=True,
    )

    spots = models.IntegerField(
        help_text="""Number of top spots which qualify""",
        null=True,
        blank=True,
    )

    description = models.TextField(
        help_text="""
            The Public description of the award.""",
        blank=True,
        max_length=1000,
    )

    notes = models.TextField(
        help_text="""
            Private Notes (for internal use only).""",
        blank=True,
    )

    DIVISION = Choices(
        (10, 'evgd1', 'EVG Division I'),
        (20, 'evgd2', 'EVG Division II'),
        (30, 'evgd3', 'EVG Division III'),
        (40, 'evgd4', 'EVG Division IV'),
        (50, 'evgd5', 'EVG Division V'),
        (60, 'fwdaz', 'FWD Arizona'),
        (70, 'fwdne', 'FWD Northeast'),
        (80, 'fwdnw', 'FWD Northwest'),
        (90, 'fwdse', 'FWD Southeast'),
        (100, 'fwdsw', 'FWD Southwest'),
        (110, 'lol10l', 'LOL 10000 Lakes'),
        (120, 'lolone', 'LOL Division One'),
        (130, 'lolnp', 'LOL Northern Plains'),
        (140, 'lolpkr', 'LOL Packerland'),
        (150, 'lolsw', 'LOL Southwest'),
        # (160, 'madatl', 'MAD Atlantic'),
        (170, 'madcen', 'MAD Central'),
        (180, 'madnth', 'MAD Northern'),
        (190, 'madsth', 'MAD Southern'),
        # (200, 'madwst', 'MAD Western'),
        (210, 'nedgp', 'NED Granite and Pine'),
        (220, 'nedmtn', 'NED Mountain'),
        (230, 'nedpat', 'NED Patriot'),
        (240, 'nedsun', 'NED Sunrise'),
        (250, 'nedyke', 'NED Yankee'),
        (260, 'swdne', 'SWD Northeast'),
        (270, 'swdnw', 'SWD Northwest'),
        (280, 'swdse', 'SWD Southeast'),
        (290, 'swdsw', 'SWD Southwest'),
    )

    division = models.IntegerField(
        choices=DIVISION,
        null=True,
        blank=True,
    )

    AGE = Choices(
        (10, 'seniors', 'Seniors',),
        (20, 'novice', 'Novice',),
        (30, 'youth', 'Youth',),
    )

    age = models.IntegerField(
        choices=AGE,
        null=True,
        blank=True,
    )

    is_novice = models.BooleanField(
        default=False,
    )

    SIZE = Choices(
        (100, 'p1', 'Plateau 1',),
        (110, 'p2', 'Plateau 2',),
        (120, 'p3', 'Plateau 3',),
        (130, 'p4', 'Plateau 4',),
        (140, 'pa', 'Plateau A',),
        (150, 'paa', 'Plateau AA',),
        (160, 'paaa', 'Plateau AAA',),
        (170, 'paaaa', 'Plateau AAAA',),
        (180, 'pb', 'Plateau B',),
        (190, 'pi', 'Plateau I',),
        (200, 'pii', 'Plateau II',),
        (210, 'piii', 'Plateau III',),
        (220, 'piv', 'Plateau IV',),
        (230, 'small', 'Small',),
    )

    size = models.IntegerField(
        choices=SIZE,
        null=True,
        blank=True,
    )

    size_range = IntegerRangeField(
        null=True,
        blank=True,
    )

    SCOPE = Choices(
        (100, 'p1', 'Plateau 1',),
        (110, 'p2', 'Plateau 2',),
        (120, 'p3', 'Plateau 3',),
        (130, 'p4', 'Plateau 4',),
        (140, 'pa', 'Plateau A',),
        (150, 'paa', 'Plateau AA',),
        (160, 'paaa', 'Plateau AAA',),
        (170, 'paaaa', 'Plateau AAAA',),
        (175, 'paaaaa', 'Plateau AAAAA',),
    )

    scope = models.IntegerField(
        choices=SCOPE,
        null=True,
        blank=True,
    )

    scope_range = FloatRangeField(
        null=True,
        blank=True,
    )

    # Denormalizations
    tree_sort = models.IntegerField(
        unique=True,
        blank=True,
        null=True,
        editable=False,
    )

    # FKs
    group = models.ForeignKey(
        'bhs.group',
        related_name='awards',
        on_delete=models.CASCADE,
    )

    parent = models.ForeignKey(
        'self',
        help_text="""If a qualifier, this is the award qualifying for.""",
        related_name='children',
        null=True,
        blank=True,
        db_index=True,
        on_delete=models.SET_NULL,
    )

    # Internals
    objects = AwardManager()

    class Meta:
        ordering = [
            'tree_sort',
        ]

    class JSONAPIMeta:
        resource_name = "award"

    def __str__(self):
        return self.name

    def clean(self):
        if self.level == self.LEVEL.qualifier and not self.threshold:
            raise ValidationError(
                {'level': 'Qualifiers must have thresholds'}
            )
        # if self.level != self.LEVEL.qualifier and self.threshold:
        #     raise ValidationError(
        #         {'level': 'Non-Qualifiers must not have thresholds'}
        #     )

    # Award Permissions
    @staticmethod
    @allow_staff_or_superuser
    @authenticated_users
    def has_read_permission(request):
        return True

    @allow_staff_or_superuser
    @authenticated_users
    def has_object_read_permission(self, request):
        return True

    @staticmethod
    @allow_staff_or_superuser
    @authenticated_users
    def has_write_permission(request):
        return any([
            request.user.is_award_manager,
        ])

    @allow_staff_or_superuser
    @authenticated_users
    def has_object_write_permission(self, request):
        return any([
            request.user.is_award_manager,
        ])

    # Transitions
    @fsm_log_by
    @transition(field=status, source='*', target=STATUS.active)
    def activate(self, *args, **kwargs):
        """Activate the Award."""
        return

    @fsm_log_by
    @transition(field=status, source='*', target=STATUS.inactive)
    def deactivate(self, *args, **kwargs):
        """Deactivate the Award."""
        return
Пример #17
0
class Station(models.Model):
    name = models.CharField(max_length=100)
    expedition = models.ForeignKey(Expedition, on_delete=models.CASCADE)

    # Date management:
    # In initial data, we have messy and sometimes imprecise dates in two fields (date and year)
    # - Those two are imported in the raw initial_date and initial_year fields (read-only so they can't be changed after
    # import)
    # For 'real app use', we use the capture_date_start and capture_date_end date fields (avoided Postgres native
    # daterange type, since it always returns [,) intervals.
    #
    # At import, we try to figure out the messy things in raw_* fields to populate capture_date_start and
    # capture_date_end.
    #
    # For DarwinCore export, we'll probably show a single date when capture_date_start == capture_date_end.
    initial_capture_year = models.CharField(max_length=5, blank=True)
    initial_capture_date = models.CharField(max_length=100, blank=True)
    capture_date_start = models.DateField(null=True, blank=True, validators=[plausible_specimen_date])
    capture_date_end = models.DateField(null=True, blank=True, validators=[plausible_specimen_date])

    coordinates = models.PointField(blank=True, null=True)
    depth = FloatRangeField(blank=True, null=True, help_text="Unit: meters.")

    gear = models.ForeignKey(Gear, blank=True, null=True, on_delete=models.CASCADE)

    objects = StationManager()

    def __str__(self):
        return "{station_name} ({expedition_name})".format(station_name=self.name, expedition_name=self.expedition.name)

    def clean(self):
        if ((self.capture_date_start and not self.capture_date_end) or
                (not self.capture_date_start and self.capture_date_end)):

            raise ValidationError("Both capture dates (or none) should be set!")

        if ((self.capture_date_start and self.capture_date_end) and
                (self.capture_date_end < self.capture_date_start)):
            raise ValidationError("Start date should be earlier than end date!")


    def long_str(self):
        return "{name} (from exp. {exp_name}) Point={coordinates} Depth={depth} Gear={gear} Initial year={i_year} Initial date={i_date} start_date={s_date} end_date={e_date}".format(
            name=self.name,
            exp_name=self.expedition,
            coordinates=self.coordinates_str(),
            depth=self.depth_str(),
            gear=self.gear,
            i_year=self.initial_capture_year,
            i_date=self.initial_capture_date,
            s_date=self.capture_date_start,
            e_date=self.capture_date_end
            )

    def depth_str(self):
        if self.depth:
            if self.depth.lower == self.depth.upper: # Single value
                str = "{depth}m.".format(depth=self.depth.lower)
            else:  # Real range
                str = '{min_depth}-{max_depth}m.'.format(min_depth=self.depth.lower, max_depth=self.depth.upper)
        else:  # No data
            str = '-'

        return str

    depth_str.short_description = 'Depth'

    def coordinates_str(self):
        if self.coordinates:
            return "{lat}, {lon}".format(lat=self.coordinates.y, lon=self.coordinates.x)

        return '-'

    coordinates_str.short_description = 'Coordinates'
Пример #18
0
class Job(CommonFieldsMixin):
    """Job post associated with project."""

    related_name = 'jobs'
    related_query_name = 'job'

    created_by = models.ForeignKey(User,
                                   db_index=True,
                                   related_name='created_jobs',
                                   related_query_name='created_job',
                                   on_delete=models.CASCADE)
    group = models.ForeignKey(Group,
                              null=True,
                              blank=True,
                              related_name=related_name,
                              related_query_name=related_query_name)

    applicants = models.ManyToManyField(User,
                                        through='application.Application',
                                        related_name=related_name,
                                        related_query_name=related_query_name)

    role_position = models.CharField(
        null=True,
        blank=True,
        max_length=255,
        help_text=
        'For eg. lead character, supporting character, background dancer etc.')
    ages = IntegerRangeField(null=True,
                             blank=True,
                             help_text='Age range required for this role.')
    required_gender = models.CharField(max_length=2,
                                       choices=choices.GENDER_CHOICES,
                                       default=choices.NOT_SPECIFIED)
    required_tokens = models.IntegerField(
        default=5,
        help_text='How much tokens user needs to have to apply to this job.')
    location = models.ForeignKey(
        City,
        null=True,
        blank=True,
        help_text="Location of user's project experience.")
    required_information_to_apply = hstore.DictionaryField(null=True,
                                                           blank=True)
    reason_for_rejection = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text='Reason why the job was rejected/unapproved by stageroute.')
    submission_deadline = models.DateField(
        null=True, blank=True, help_text='Date for the job deadline.')

    status = models.CharField(max_length=2,
                              choices=choices.JOB_STATE_CHOICES,
                              default=choices.PENDING_APPROVAL)
    number_of_vacancies = models.IntegerField(
        default=1, help_text='How many positions are open for this job.')
    budgets = IntegerRangeField(
        null=True,
        blank=True,
        help_text='budget range amount to be spent on the job.')
    featured = models.BooleanField(default=False, help_text='Is job featured.')
    skin_type = models.CharField(max_length=50,
                                 null=True,
                                 blank=True,
                                 default=choices.DOES_NOT_MATTER,
                                 choices=choices.SKIN_TYPE_CHOICES,
                                 help_text='Preferred skin type.')
    hair_type = models.CharField(max_length=50,
                                 null=True,
                                 blank=True,
                                 default=choices.DOES_NOT_MATTER,
                                 choices=choices.HAIR_TYPE_CHOICES,
                                 help_text='Preferred hair type.')
    eye_color = models.CharField(max_length=50,
                                 default=choices.DOES_NOT_MATTER,
                                 null=True,
                                 blank=True,
                                 choices=choices.EYE_COLOR_CHOICES,
                                 help_text='Peferred eye color.')
    hair_color = models.CharField(max_length=50,
                                  default=choices.DOES_NOT_MATTER,
                                  null=True,
                                  blank=True,
                                  choices=choices.HAIR_COLOR_CHOICES,
                                  help_text='Peferred eye color.')
    hair_style = models.CharField(max_length=50,
                                  default=choices.DOES_NOT_MATTER,
                                  null=True,
                                  blank=True,
                                  choices=choices.HAIR_STYLE_CHOICES,
                                  help_text='Peferred eye color.')
    heights = FloatRangeField(null=True,
                              blank=True,
                              help_text='Range of height required.')
    body_type = models.CharField(max_length=50,
                                 null=True,
                                 blank=True,
                                 default=choices.DOES_NOT_MATTER,
                                 choices=choices.BODY_TYPES)
    language = models.CharField(max_length=50,
                                null=True,
                                blank=True,
                                default=choices.DOES_NOT_MATTER,
                                choices=choices.LANGUAGE_CHOICES,
                                help_text='Preferred languages.')

    job_type = models.CharField(max_length=50,
                                null=True,
                                blank=True,
                                choices=choices.JOB_TYPE_CHOICES,
                                help_text='Type of job.')
    auditions_per_day = models.IntegerField(
        null=True,
        blank=True,
        help_text='Number of auditions to do per day for this job.')
    audition_range = DateRangeField(null=True,
                                    blank=True,
                                    help_text='Audition range')
    job_owner_email = models.EmailField(
        null=True,
        blank=True,
        help_text='Should be valid email, e.g. [email protected]',
    )
    job_owner_phone = models.CharField(max_length=10,
                                       null=True,
                                       blank=True,
                                       db_index=True,
                                       help_text="User's phone number.")
    notes = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        help_text="Useful for job posters. A quick note they can refere later."
    )
    field_history = FieldHistoryTracker(['status'])
    related_query_name = 'jobs'

    images = GenericRelation(Image, related_query_name=related_query_name)
    videos = GenericRelation(Video, related_query_name=related_query_name)
    audios = GenericRelation(Audio, related_query_name=related_query_name)
    objects = hstore.HStoreManager()

    def __unicode__(self):
        """unicode."""
        return self.title
Пример #19
0
 class RangesModel(models.Model):
     ints = IntegerRangeField(blank=True, null=True)
     bigints = BigIntegerRangeField(blank=True, null=True)
     floats = FloatRangeField(blank=True, null=True)
     timestamps = DateTimeRangeField(blank=True, null=True)
     dates = DateRangeField(blank=True, null=True)
Пример #20
0
class Award(TimeStampedModel):
    """
    Award Model.

    The specific award conferred by a Group.
    """

    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )

    name = models.CharField(
        help_text="""Award Name.""",
        max_length=255,
    )

    STATUS = Choices(
        (
            -10,
            'inactive',
            'Inactive',
        ),
        (
            0,
            'new',
            'New',
        ),
        (
            10,
            'active',
            'Active',
        ),
    )

    status = FSMIntegerField(
        help_text=
        """DO NOT CHANGE MANUALLY unless correcting a mistake.  Use the buttons to change state.""",
        choices=STATUS,
        default=STATUS.new,
    )

    KIND = Choices(
        (32, 'chorus', "Chorus"),
        (41, 'quartet', "Quartet"),
    )

    kind = models.IntegerField(choices=KIND, )

    GENDER = Choices(
        (10, 'male', "Male"),
        (20, 'female', "Female"),
        (30, 'mixed', "Mixed"),
    )

    gender = models.IntegerField(
        help_text="""
            The gender of session.
        """,
        choices=GENDER,
        default=GENDER.male,
    )

    LEVEL = Choices(
        (10, 'championship', "Championship"),
        (30, 'qualifier', "Qualifier"),
        (35, 'top', "Top"),
        (40, 'award', "Award"),
        (45, 'representative', "Representative"),
        (50, 'deferred', "Deferred"),
        (60, 'manual', "Manual"),
    )

    level = models.IntegerField(choices=LEVEL, )

    SEASON = Choices(
        (
            1,
            'summer',
            'Summer',
        ),
        (
            2,
            'midwinter',
            'Midwinter',
        ),
        (
            3,
            'fall',
            'Fall',
        ),
        (
            4,
            'spring',
            'Spring',
        ),
        (
            9,
            'video',
            'Video',
        ),
    )

    season = models.IntegerField(choices=SEASON, )

    rounds = models.IntegerField(
        help_text="""Number of rounds to determine the championship""", )

    threshold = models.FloatField(
        help_text="""
            The score threshold for automatic qualification (if any.)
        """,
        null=True,
        blank=True,
    )

    minimum = models.FloatField(
        help_text="""
            The minimum score required for qualification (if any.)
        """,
        null=True,
        blank=True,
    )

    advance = models.FloatField(
        help_text="""
            The score threshold to advance to next round (if any) in
            multi-round qualification.
        """,
        null=True,
        blank=True,
    )

    spots = models.IntegerField(
        help_text="""Number of top spots which qualify""",
        null=True,
        blank=True,
    )

    description = models.TextField(
        help_text="""
            The Public description of the award.""",
        blank=True,
        max_length=1000,
    )

    notes = models.TextField(
        help_text="""
            Private Notes (for internal use only).""",
        blank=True,
    )

    AGE = Choices(
        (
            10,
            'seniors',
            'Seniors',
        ),
        (
            30,
            'youth',
            'Youth',
        ),
    )

    age = models.IntegerField(
        choices=AGE,
        null=True,
        blank=True,
    )

    SIZE = Choices(
        (
            100,
            'p1',
            'Plateau 1',
        ),
        (
            110,
            'p2',
            'Plateau 2',
        ),
        (
            120,
            'p3',
            'Plateau 3',
        ),
        (
            130,
            'p4',
            'Plateau 4',
        ),
        (
            140,
            'pa',
            'Plateau A',
        ),
        (
            150,
            'paa',
            'Plateau AA',
        ),
        (
            160,
            'paaa',
            'Plateau AAA',
        ),
        (
            170,
            'paaaa',
            'Plateau AAAA',
        ),
        (
            180,
            'pb',
            'Plateau B',
        ),
        (
            190,
            'pi',
            'Plateau I',
        ),
        (
            200,
            'pii',
            'Plateau II',
        ),
        (
            210,
            'piii',
            'Plateau III',
        ),
        (
            220,
            'piv',
            'Plateau IV',
        ),
        (
            230,
            'small',
            'Small',
        ),
    )

    size = models.IntegerField(
        choices=SIZE,
        null=True,
        blank=True,
    )

    size_range = IntegerRangeField(
        null=True,
        blank=True,
    )

    SCOPE = Choices(
        (
            100,
            'p1',
            'Plateau 1',
        ),
        (
            110,
            'p2',
            'Plateau 2',
        ),
        (
            120,
            'p3',
            'Plateau 3',
        ),
        (
            130,
            'p4',
            'Plateau 4',
        ),
        (
            140,
            'pa',
            'Plateau A',
        ),
        (
            150,
            'paa',
            'Plateau AA',
        ),
        (
            160,
            'paaa',
            'Plateau AAA',
        ),
        (
            170,
            'paaaa',
            'Plateau AAAA',
        ),
        (
            175,
            'paaaaa',
            'Plateau AAAAA',
        ),
    )

    scope = models.IntegerField(
        choices=SCOPE,
        null=True,
        blank=True,
    )

    scope_range = FloatRangeField(
        null=True,
        blank=True,
    )

    # Denormalizations
    tree_sort = models.IntegerField(
        unique=True,
        blank=True,
        null=True,
        editable=False,
    )

    # FKs
    group = models.ForeignKey(
        'Group',
        related_name='awards',
        on_delete=models.CASCADE,
    )

    parent = models.ForeignKey(
        'self',
        help_text="""If a qualifier, this is the award qualifying for.""",
        related_name='children',
        null=True,
        blank=True,
        db_index=True,
        on_delete=models.SET_NULL,
    )

    # Internals
    objects = AwardManager()

    class Meta:
        ordering = [
            'tree_sort',
        ]

    class JSONAPIMeta:
        resource_name = "award"

    def __str__(self):
        return self.name

    def clean(self):
        pass
        # if self.level == self.LEVEL.qualifier and not self.threshold:
        #     raise ValidationError(
        #         {'level': 'Qualifiers must have thresholds'}
        #     )
        # if self.level != self.LEVEL.qualifier and self.threshold:
        #     raise ValidationError(
        #         {'level': 'Non-Qualifiers must not have thresholds'}
        #     )

    # Award Permissions
    @staticmethod
    @allow_staff_or_superuser
    @authenticated_users
    def has_read_permission(request):
        return True

    @allow_staff_or_superuser
    @authenticated_users
    def has_object_read_permission(self, request):
        return True

    @staticmethod
    @allow_staff_or_superuser
    @authenticated_users
    def has_write_permission(request):
        return any([
            request.user.is_award_manager,
        ])

    @allow_staff_or_superuser
    @authenticated_users
    def has_object_write_permission(self, request):
        return any([
            request.user.is_award_manager,
        ])

    # Transitions
    @fsm_log_by
    @transition(field=status, source='*', target=STATUS.active)
    def activate(self, *args, **kwargs):
        """Activate the Award."""
        return

    @fsm_log_by
    @transition(field=status, source='*', target=STATUS.inactive)
    def deactivate(self, *args, **kwargs):
        """Deactivate the Award."""
        return
Пример #21
0
class DataType(models.Model):
    """
    A model of reading's data type. There may be multiple sensors which share a single data type; for example,
    temperature.
    """

    DEGREES_CENTIGRADE = "°C"
    DEGREES_FAHRENHEIT = "°F"
    KELVIN = "K"

    KILOMETRES = "km"
    METRES = "m"
    CENTIMETRES = "cm"
    MILLIMETRES = "mm"

    DEGREES = "°"
    RADIANS = "rad"

    METRES_PER_SECOND = "m/s"
    KILOMETRES_PER_HOUR = "km/h"

    KILOPASCALS = "kPa"
    HECTOPASCALS = "hPa"
    PASCALS = "Pa"
    BAR = "bar"
    MILLIBAR = "mbar"

    WATTS_PER_SQUARE_METRE = "W/m^2"

    VOLTS = "V"
    AMPERES = "A"
    OHMS = "Ω"
    JOULES = "J"
    WATTS = "W"

    PERCENT = "%"
    NONE = None

    UNIT_CHOICES = (
        # Temperature
        (DEGREES_CENTIGRADE, "degrees Celcius"),
        (DEGREES_FAHRENHEIT, "degrees Fahrenheit"),
        (KELVIN, "kelvin"),

        # Distance / Depth
        (KILOMETRES, "kilometres"),
        (METRES, "metres"),
        (CENTIMETRES, "centimetres"),
        (MILLIMETRES, "millimetres"),

        # Direction
        (DEGREES, "degrees"),
        (RADIANS, "radians"),

        # Speed / Velocity
        (METRES_PER_SECOND, "metres per second"),
        (KILOMETRES_PER_HOUR, "kilometres per hour"),

        # Pressure
        (KILOPASCALS, "kilopascals"),
        (HECTOPASCALS, "hectopascals"),
        (PASCALS, "pascals"),
        (BAR, "bar"),
        (MILLIBAR, "millibar"),

        # Irradiance
        (WATTS_PER_SQUARE_METRE, "Watts per square metre"),

        # Electricity
        (VOLTS, "volts"),
        (AMPERES, "amperes"),
        (OHMS, "ohms"),
        (JOULES, "joules"),
        (WATTS, "watts"),

        # Other / Miscellaneous
        (PERCENT, "percent"),
        (NONE, "none"),
    )

    def bounds_str(self):
        return "[{},{})".format(self.bounds.lower, self.bounds.upper)

    bounds_str.short_description = "Bounds"

    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    # For downloaded data, the full name would be unwieldy, so also include a unique short name.
    name = models.CharField(max_length=100)
    short_name = models.CharField(max_length=20, unique=True, db_index=True)

    unit = models.CharField(max_length=40, choices=UNIT_CHOICES, null=True)
    bounds = FloatRangeField(default="[{},{})".format(-(2**31), (2**31 - 1)))

    def __repr__(self):
        return "<DataType {} ({})>".format(self.name, self.short_name)

    def __str__(self):
        return self.name