Beispiel #1
0
class A125(models.Model):

    date_filled = models.DateField(null=False)
    professor = models.ForeignKey(User)

    name = models.CharField(max_length=50, null=True)
    ssn = models.IntegerField(max_length=9, null=True)
    title = models.CharField(max_length=1, null=True)
    base_salary = models.FloatField(null=True)
    period = models.CharField(max_length=1, null=True)
    period_year = models.CharField(max_length=4, null=True)
    effective_date = models.DateField(null=True)
    multi_campus = models.BooleanField()

    # Modulo 5
    sponsored_accounts = ArrayField(dbtype='text')
    # Modulo 5
    cost_sharing = ArrayField(dbtype='text')
    # Modulo 5
    university_funds = ArrayField(dbtype='text')
    # Only 2 entries
    total_compensation = ArrayField(dbtype='text')
    # Modulo 3
    payments_paid = ArrayField(dbtype='text')

    comments = models.TextField(null=True)
    objects = ExpressionManager()

    def __unicode__(self):
        return u'%s %s: %s' % (self.professor.first_name,
                               self.professor.last_name, self.date_filled)
Beispiel #2
0
        def test_deconstruct_custom(self):
            """Attributes at custom values included in deconstruction."""
            af = ArrayField(
                dbtype='text',
                dimension=2,
                type_cast=custom_type_cast,
                blank=False,
                null=False,
                default=[['a'], ['b']],
            )

            name, path, args, kwargs = af.deconstruct()

            naf = ArrayField(*args, **kwargs)

            self.assertEqual(args, [])
            self.assertEqual(
                kwargs,
                {
                    'dbtype': 'text',
                    'dimension': 2,
                    'type_cast': custom_type_cast,
                    'blank': False,
                    'null': False,
                    'default': [['a'], ['b']],
                },
            )
            self.assertEqual(af._array_type, naf._array_type)
            self.assertEqual(af._dimension, naf._dimension)
            self.assertEqual(af._type_cast, naf._type_cast)
            self.assertEqual(af.blank, naf.blank)
            self.assertEqual(af.null, naf.null)
            self.assertEqual(af.default, naf.default)
Beispiel #3
0
        def test_deconstruct_custom(self):
            """Attributes at custom values included in deconstruction."""
            af = ArrayField(
                dbtype='text',
                dimension=2,
                type_cast=custom_type_cast,
                blank=False,
                null=False,
                default=[['a'], ['b']],
            )

            name, path, args, kwargs = af.deconstruct()

            naf = ArrayField(*args, **kwargs)

            self.assertEqual(args, [])
            self.assertEqual(
                kwargs,
                {
                    'dbtype': 'text',
                    'dimension': 2,
                    'type_cast': custom_type_cast,
                    'blank': False,
                    'null': False,
                    'default': [['a'], ['b']],
                },
            )
            self.assertEqual(af._array_type, naf._array_type)
            self.assertEqual(af._dimension, naf._dimension)
            self.assertEqual(af._type_cast, naf._type_cast)
            self.assertEqual(af.blank, naf.blank)
            self.assertEqual(af.null, naf.null)
            self.assertEqual(af.default, naf.default)
Beispiel #4
0
 def test_can_override_formfield(self):
     model_field = ArrayField()
     class FakeFieldClass(object):
         def __init__(self, *args, **kwargs):
             pass
     form_field = model_field.formfield(form_class=FakeFieldClass)
     self.assertIsInstance(form_field, FakeFieldClass)
Beispiel #5
0
        def test_deconstruct_unknown_dbtype(self):
            """Deconstruction does not include type_cast if dbtype unknown."""
            af = ArrayField(dbtype='foo')

            name, path, args, kwargs = af.deconstruct()

            naf = ArrayField(*args, **kwargs)

            self.assertEqual(kwargs, {'dbtype': 'foo'})
Beispiel #6
0
    def test_can_override_formfield(self):
        model_field = ArrayField()

        class FakeFieldClass(object):
            def __init__(self, *args, **kwargs):
                pass

        form_field = model_field.formfield(form_class=FakeFieldClass)
        self.assertIsInstance(form_field, FakeFieldClass)
Beispiel #7
0
        def test_deconstruct_unknown_dbtype(self):
            """Deconstruction does not include type_cast if dbtype unknown."""
            af = ArrayField(dbtype='foo')

            name, path, args, kwargs = af.deconstruct()

            naf = ArrayField(*args, **kwargs)

            self.assertEqual(kwargs, {'dbtype': 'foo'})
Beispiel #8
0
class Dataset(models.Model):  # dcat:Dataset
    # Identification and common fields
    division_id = models.CharField(max_length=150, db_index=True)
    name = models.CharField(
        max_length=500
    )  # @see https://github.com/ckan/ckan/blob/525fd7d4c6d9987504d2d20c383b83382cefcab3/ckan/model/package.py#L29
    json = JSONField(default={})
    custom_properties = ArrayField(dbtype='text')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    # Additional fields
    source_url = models.URLField(unique=True, max_length=500)
    extras = JSONField(default={})
    extras_keys = ArrayField(dbtype='text')

    # @see http://www.w3.org/TR/vocab-dcat/
    title = models.TextField(default='')  # dct
    description = models.TextField(default='')  # dct
    issued = models.DateTimeField(null=True)  # dct
    modified = models.DateTimeField(null=True)  # dct
    language = models.TextField(default='')  # dct
    publisher = models.TextField(default='')  # dct
    accrualPeriodicity = models.TextField(default='')  # dct
    identifier = models.TextField(default='')  # dct (not always a UUID)
    spatial = models.TextField(default='')  # dct
    temporal = models.TextField(default='')  # dct
    theme = ArrayField(dbtype='text')  # dcat
    keyword = ArrayField(dbtype='text')  # dcat
    contactPoint = models.TextField(default='')  # dcat
    landingPage = models.URLField(default='',
                                  max_length=500)  # dcat (length 401 observed)

    # CKAN
    type = models.TextField(default='')

    # @see http://project-open-data.github.io/v1.1/schema/#accessLevel
    accessLevel = models.TextField(default='')

    # License properties
    isopen = models.NullBooleanField()
    license_id = models.TextField(default='')
    license_url = models.URLField(default='')
    license_title = models.TextField(default='')
    license = models.URLField(default='', db_index=True)

    class Meta:
        unique_together = (('division_id', 'name'), )

    def __str__(self):
        return '{}: {}'.format(self.division_id, self.name)

    @property
    def ckan_dataset_url(self):
        return self.source_url.replace('/api/3/action/package_show?id=',
                                       '/dataset/')
Beispiel #9
0
        def test_deconstruct_defaults(self):
            """Attributes at default values left out of deconstruction."""
            af = ArrayField()

            name, path, args, kwargs = af.deconstruct()

            naf = ArrayField(*args, **kwargs)

            self.assertEqual((args, kwargs), ([], {}))
            self.assertEqual(af._array_type, naf._array_type)
            self.assertEqual(af._dimension, naf._dimension)
            self.assertEqual(af._type_cast, naf._type_cast)
            self.assertEqual(af.blank, naf.blank)
            self.assertEqual(af.null, naf.null)
            self.assertEqual(af.default, naf.default)
Beispiel #10
0
        def test_deconstruct_defaults(self):
            """Attributes at default values left out of deconstruction."""
            af = ArrayField()

            name, path, args, kwargs = af.deconstruct()

            naf = ArrayField(*args, **kwargs)

            self.assertEqual((args, kwargs), ([], {}))
            self.assertEqual(af._array_type, naf._array_type)
            self.assertEqual(af._dimension, naf._dimension)
            self.assertEqual(af._type_cast, naf._type_cast)
            self.assertEqual(af.blank, naf.blank)
            self.assertEqual(af.null, naf.null)
            self.assertEqual(af.default, naf.default)
Beispiel #11
0
class Distribution(models.Model):  # dcat:Distribution
    # Identification and common fields
    dataset = models.ForeignKey('Dataset')
    _id = models.TextField(default='')  # (not always a UUID)
    json = JSONField(default={})
    custom_properties = ArrayField(dbtype='text')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    # Additional fields
    division_id = models.CharField(max_length=150, db_index=True)

    # @see http://www.w3.org/TR/vocab-dcat/
    title = models.TextField(default='')  # dct
    description = models.TextField(default='')  # dct
    issued = models.DateTimeField(null=True)  # dct
    modified = models.DateTimeField(null=True)  # dct
    license = models.URLField(default='', db_index=True)  # dct
    accessURL = models.URLField(default='',
                                max_length=2000)  # dcat (length 1692 observed)
    byteSize = models.BigIntegerField(null=True)  # dcat
    format = models.TextField(default='')  # dct
    mediaType = models.TextField(default='', db_index=True)  # dcat

    # CKAN
    mimetype = models.TextField(default='')
    mimetype_inner = models.TextField(default='')

    # HTTP headers
    http_headers = JSONField(default={})
    http_status_code = models.SmallIntegerField(null=True)
    http_content_length = models.BigIntegerField(null=True)
    http_content_type = models.TextField(default='')
    http_charset = models.TextField(default='')

    # CSV validation
    valid = models.NullBooleanField(null=True)
    errors = ArrayField(dbtype='text')

    class Meta:
        unique_together = (('dataset', '_id'), )
        index_together = (
            ('dataset', 'mediaType'),
            ('dataset', 'division_id', 'mediaType'),
        )

    def __str__(self):
        return '{}: {} {}'.format(self.division_id, self.dataset, self._id)
Beispiel #12
0
class Occurrence(models.Model):
    _database = 'lifeten'
    id = models.IntegerField(primary_key=True, db_column='occurrence_pk')
    specie = models.ForeignKey(Species,
                               null=True,
                               db_column='specie',
                               blank=True)
    datasetrowid = models.IntegerField(null=True, blank=True)
    basisofrecord = models.CharField(max_length=50)
    eventdate = models.DateField(null=True, blank=True)
    coordinateuncertaintyinmeters = models.IntegerField(null=True, blank=True)
    individualcount = models.IntegerField()
    monitoringprogramme = models.CharField(max_length=100, blank=True)
    wkb_geometry = models.PointField(srid=25832)
    datasetid = models.ForeignKey(Datasetinfo,
                                  null=True,
                                  db_column='datasetid',
                                  blank=True)
    sex = ArrayField(blank=True, dbtype="int", dimension=2)
    recorder_1 = models.ForeignKey(Recorderinfo,
                                   null=True,
                                   related_name='+',
                                   db_column='recorder_1',
                                   blank=True)
    recorder_2 = models.ForeignKey(Recorderinfo,
                                   null=True,
                                   related_name='+',
                                   db_column='recorder_2',
                                   blank=True)
    recorder_3 = models.ForeignKey(Recorderinfo,
                                   null=True,
                                   related_name='+',
                                   db_column='recorder_3',
                                   blank=True)
    recorder_4 = models.ForeignKey(Recorderinfo,
                                   null=True,
                                   related_name='+',
                                   db_column='recorder_4',
                                   blank=True)
    lifestage = ArrayField(blank=True, dbtype="int", dimension=7)
    locality = models.CharField(max_length=1000, blank=True)
    eventtime = models.TimeField(null=True, blank=True)
    original_geom = models.GeometryField(srid=25832, null=True, blank=True)
    objects = models.GeoManager()

    class Meta:
        db_table = u'occurrence2'
Beispiel #13
0
class UserCount(models.Model):
    """Number of users in a channel, per hour."""

    channel = models.ForeignKey(Channel)
    dt = models.DateField()
    counts = ArrayField(dbtype="int")

    def __unicode__(self):
        return "{} on {}: {}".format(self.channel, self.dt, self.counts)
class Bill(OCDBase):
    id = OCDIDField(ocd_type='bill')
    legislative_session = models.ForeignKey(LegislativeSession,
                                            related_name='bills')
    identifier = models.CharField(max_length=100)

    title = models.TextField()

    from_organization = models.ForeignKey(Organization,
                                          related_name='bills',
                                          null=True)
    classification = ArrayField(
        dbtype="text")  # check that array values are in enum?
    subject = ArrayField(dbtype="text")

    def __str__(self):
        return '{} in {}'.format(self.identifier, self.legislative_session)

    class Meta:
        index_together = [
            ['from_organization', 'legislative_session', 'identifier'],
        ]

    # ------------------------------------------------------------------------
    # Display methods used in the admin.
    # ------------------------------------------------------------------------
    def get_jurisdiction_name(self):
        return self.legislative_session.jurisdiction.name

    def get_session_name(self):
        return self.legislative_session.name

    def get_truncated_sponsors(self):
        spons = ', '.join(s.name for s in self.sponsorships.all()[:5])
        return defaultfilters.truncatewords(spons, 10)

    def get_truncated_title(self):
        return defaultfilters.truncatewords(self.title, 25)

    get_jurisdiction_name.short_description = 'Jurisdiction'
    get_session_name.short_description = 'Session'
    get_truncated_sponsors.short_description = 'Sponsors'
    get_truncated_title.short_description = 'Title'
class BillAction(RelatedBase):
    bill = models.ForeignKey(Bill, related_name='actions')
    organization = models.ForeignKey(Organization, related_name='actions')
    description = models.TextField()
    date = models.CharField(max_length=10)  # YYYY[-MM[-DD]]
    classification = ArrayField(dbtype="text")  # enum
    order = models.PositiveIntegerField()

    class Meta:
        ordering = ['order']
Beispiel #16
0
class Profile(models.Model):

    # Primary key is User model
    professor = models.OneToOneField(User, primary_key=True)

    # Faculty the professor pertains to f11
    Facultad = ArrayField(dbtype='text')
    # Numero de Plaza of the professor f12
    NumPlaza = ArrayField(dbtype='text')
    # Title of the Professor f14
    Titulo_Rango = ArrayField(dbtype='text')
    # Scale rate f18
    Escala_Rate = ArrayField(dbtype='text')
    # Total salary f19
    SueldoTotal = ArrayField(dbtype='int')

    objects = ExpressionManager()

    def __unicode__(self):
        return u"%s's profile" % self.professor.first_name
Beispiel #17
0
class IrregularlySampledSignal(DataModel):
    '''
    
    A representation of a continuous, analog signal acquired at time 
    t_start with a varying sampling interval.

    '''

    recording_channel = models.ForeignKey(RecordingChannel)

    times = ArrayField(dbtype="float(53)", dimension=1)
    t_units = models.CharField(max_length=16, choices=TIME_CHOICES, blank=True)
    signal = ArrayField(dbtype="float(53)", dimension=1)  # dimensions: [time]
    signal_units = models.CharField(max_length=255,
                                    choices=POTENTIAL_CHOICES +
                                    CURRENT_CHOICES,
                                    blank=True)

    def __unicode__(self):
        return str(len(self.times))
Beispiel #18
0
class SpikeTrainFull(SpikeTrain):
    '''
    the optional waveforms
    '''

    waveforms = ArrayField(dbtype="float(53)",
                           dimension=3)  #  dimensions: [spike,channel,time]
    waveform_units = models.CharField(max_length=255,
                                      choices=POTENTIAL_CHOICES)
    sampling_rate = models.FloatField(null=True, blank=True)
    left_sweep = models.FloatField(null=True, blank=True)
    sort = models.BooleanField(default=False)
Beispiel #19
0
class Event(models.Model):
    objects = EventManager()

    author = models.ForeignKey(User, null=True, blank=True)
    title = models.CharField(u'Naslov', max_length=192)
    fbeventid = models.CharField(
        u'Facebook Event ID',
        null=True,
        blank=True,
        max_length=25,
        help_text='Pročitati iz adresne trake (URL) na Facebooku')
    date = models.DateField(u'Datum')
    time = models.TimeField(u'Vrijeme', null=True, blank=True)
    description = HTMLField(u'Opis', blank=True)
    content = HTMLField(u'Sadržaj', blank=True)
    tags = ArrayField(
        dbtype="text",
        help_text=
        'OBAVEZNO odvojiti tagove zarezon ali *BEZ* razmaka. Primjer: tag1,tag2,tag3'
    )
    slug = models.SlugField(blank=True, max_length=128, unique=True)
    announce = models.BooleanField(u'Najavi')
    daytime = models.BooleanField(u'Dnevni')
    price = models.CharField(u'Cijena', max_length=16, null=True, blank=True)
    thumb = FileBrowseField(u'Sličica', max_length=255, null=True, blank=True)

    class Meta:
        verbose_name = 'događaj'
        verbose_name_plural = 'događaji'

    # rss feed uses this
    def get_absolute_url(self):
        return '/dogadaj/%s/' % self.slug

    def __unicode__(self):
        return u'%s %s' % (self.title, self.date)

    @staticmethod
    def get_frontpage_events():
        return Event.objects.filter(date__gte=datetime.now()).filter(
            daytime=False, announce=True).order_by('date')[:3]

    @staticmethod
    def get_frontpage_daytime_events():
        return Event.objects.filter(date__gte=datetime.now()).filter(
            announce=True, daytime=True).order_by('date')[:3]

    def tags_to_str(self):
        """
        Using this for list_display in admin because if tags is a list
        unicodes get messed up, but a string shows up fine
        """
        return ', '.join(self.tags)
Beispiel #20
0
class Order(models.Model):
    """ Order
    """
    PENDING = 'P'
    COMPLETED = 'C'
    FAILED = 'F'
    status_options = (
        (PENDING, 'Pending'),
        (FAILED, 'Failed'),
        (COMPLETED, 'Completed'),
    )
    function_options = (
        ('follow_user', 'Follow user'),
        ('unfollow_user', 'Unfollow user'),
        ('retweet', 'Retweet'),
        ('favourite', 'Favourite'),
    )
    user = models.ForeignKey(Twitter)
    schedule_order = models.ForeignKey(ScheduleOrder, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    executed_at = models.DateTimeField(null=True, blank=True)
    status = models.CharField(max_length=2, choices=status_options, default=PENDING)
    func = models.CharField(max_length=200, )
    args = ArrayField(dbtype='text', null=True, blank=True)
    kwargs = DictionaryField(null=True, blank=True, db_index=True)
    result = models.TextField(null=True, blank=True)

    objects = OrderManager()

    def __unicode__(self):

        try:
            return u'{0} "{1}" by {2}'.format(self.kwargs['func'].capitalize(), truncatechars(self.kwargs['tweet'], 50),
                                              self.kwargs['screen_name'])
        except KeyError:
            return u'%s' % self.func

    @property
    def kwargs_tweet(self):
        try:
            return self.kwargs['tweet']
        except:
            return None

    @property
    def kwargs_screen_name(self):
        try:
            return self.kwargs['screen_name']
        except:
            return None
Beispiel #21
0
class PortfolioProject(models.Model):
    developer = models.ForeignKey(Developer, related_name='portfolio_projects')
    title = models.CharField(max_length=255)
    description = models.TextField()
    website = models.CharField(max_length=255)
    image = models.FileField(upload_to=portfolio_project_file_upload_to,
                             blank=True,
                             null=True)
    skills = ArrayField(dbtype='varchar')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.title
class Jurisdiction(OCDBase):
    id = OCDIDField(ocd_type='jurisdiction')
    name = models.CharField(max_length=300)
    url = models.URLField(max_length=2000)
    classification = models.CharField(
        max_length=50,
        choices=JURISDICTION_CLASSIFICATION_CHOICES,
        default='government',
        db_index=True)
    feature_flags = ArrayField(dbtype="text")
    division = models.ForeignKey(Division,
                                 related_name='jurisdictions',
                                 db_index=True)

    def __str__(self):
        return self.name
Beispiel #23
0
class Route(models.Model):
    line = models.ForeignKey(Line)

    # Data
    name = models.CharField(max_length=1024, help_text=_('Nama rute'), **OPT)
    path = models.LineStringField(srid=SRID, **OPT)
    locations = ArrayField(dbtype="varchar",
                           max_length=1024,
                           help_text=_('Daerah yang dilewati rute'))
    ordering = models.IntegerField(default=0)

    # Author
    author = models.ForeignKey(Author)

    # Internal
    enabled = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name
Beispiel #24
0
class ScheduleOrder(models.Model):
    """ ScheduleOrder
    """
    function_options = (
        ('follow_user', 'Follow user'),
        ('unfollow_user', 'Unfollow user'),
        ('retweet', 'Retweet'),
        ('favourite', 'Favourite'),
    )
    status_options = (
        ('A', 'Active'),
        ('D', 'Deleted'),
        ('R', 'Running'),
        ('P', 'Pending'),
    )

    user = models.ForeignKey(Twitter)
    label = models.CharField(_('Label'), max_length=250)
    run_once = models.BooleanField(default=True)
    status = models.CharField(max_length=6, choices=status_options, default='A')
    func = models.CharField(max_length=200, choices=function_options)
    args = ArrayField(dbtype='text', null=True, blank=True)
    kwargs = DictionaryField(null=True, blank=True, db_index=True)
    data = DictionaryField(null=True, blank=True, help_text=_('Used to maintain data about process details'))
    created_at = models.DateTimeField(auto_now_add=True)
    last_run = models.DateTimeField(null=True, blank=True)

    objects = ScheduleOrderManger()

    def __unicode__(self):
        return u'%s' % self.label

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if self.run_once and self.status == 'A':
            self.status = 'P'

        super(ScheduleOrder, self).save(force_insert=force_insert, force_update=force_update, using=using,
                                        update_fields=update_fields)
Beispiel #25
0
class Developer(models.Model):
    DEVELOPER = 'DEV'
    DESIGNER = 'DES'
    TYPE_CHOICES = (
        (DEVELOPER, 'Developer'),
        (DESIGNER, 'Designer'),
    )

    AVAILABLE_NOW = 'NOW'
    AVAILABLE_CHOICES = ((AVAILABLE_NOW, 'Now'), )

    PROJECT_PREFERENCES_FLAGS = (
        (
            'small',
            'Small',
        ),
        (
            'big',
            'Big',
        ),
    )

    user = models.ForeignKey(User, unique=True, related_name='developer')
    type = MultiSelectField(choices=TYPE_CHOICES,
                            default=DEVELOPER,
                            blank=True,
                            null=True)
    title = models.CharField(max_length=255, null=True, blank=True)
    bio = models.TextField(null=True, blank=True)
    skills = ArrayField(dbtype='varchar')
    availability = models.CharField(max_length=255,
                                    choices=AVAILABLE_CHOICES,
                                    default=AVAILABLE_NOW)
    project_preferences = BitField(flags=PROJECT_PREFERENCES_FLAGS)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.user.get_full_name()
Beispiel #26
0
class SpikeTrain(DataModel):
    '''

    A set of action potentials (spikes) emitted by the same unit in a 
    period of time (with optional waveforms).

    '''
    times = ArrayField(dbtype="float(53)",
                       dimension=1)  # dimensions: [spike_time]
    t_start = models.FloatField(default=0.0)
    t_stop = models.FloatField()
    t_units = models.CharField(max_length=255,
                               choices=TIME_CHOICES,
                               blank=True)

    unit = models.ForeignKey(Unit,
                             null=True,
                             blank=True,
                             related_name='spike_trains')

    def __unicode__(self):
        return str(len(self.times))
Beispiel #27
0
class AnalogSignal(DataModel):
    '''A regular sampling of a continuous, analog signal.'''

    t_start = models.FloatField(default=0.0)
    t_units = models.CharField(max_length=16, choices=TIME_CHOICES, blank=True)
    signal = ArrayField(dbtype="float(53)", dimension=1)  # dimensions: [time]
    signal_units = models.CharField(max_length=255,
                                    choices=POTENTIAL_CHOICES +
                                    CURRENT_CHOICES,
                                    blank=True)

    recording_channel = models.ForeignKey(RecordingChannel,
                                          null=True,
                                          blank=True)

    sampling_rate = models.FloatField(blank=False)

    @property
    def sampling_period(self):
        ''' 1/sampling_rate '''
        return 1.0 / self.sampling_rate

    @sampling_period.setter
    def sampling_period(self, value):
        self.sampling_rate = 1.0 / value

    @property
    def duration(self):
        ''' len(signal)*sampling_period '''
        return float(len(self.signal)) * self.sampling_period

    @property
    def t_stop(self):
        ''' t_start + duration '''
        return self.t_start + self.duration

    def __unicode__(self):
        return self.name
Beispiel #28
0
class VoteEvent(OCDBase):
    id = OCDIDField(ocd_type='vote')
    identifier = models.CharField(max_length=300, blank=True)
    motion_text = models.TextField()
    motion_classification = ArrayField(dbtype="text")  # enum
    start_date = models.CharField(max_length=19)  # YYYY-MM-DD HH:MM:SS
    end_date = models.CharField(max_length=19, blank=True)  # YYYY-MM-DD

    result = models.CharField(max_length=50,
                              choices=common.VOTE_RESULT_CHOICES)
    organization = models.ForeignKey(Organization, related_name='votes')
    legislative_session = models.ForeignKey(LegislativeSession,
                                            related_name='votes')
    bill = models.ForeignKey(Bill, related_name='votes', null=True)

    def __str__(self):
        if self.identifier:
            return '{} in {}'.format(self.identifier, self.legislative_session)
        else:
            return '{} on {}'.format(self.motion_text, self.bill)

    class Meta:
        index_together = [['legislative_session', 'identifier', 'bill'],
                          ['legislative_session', 'bill']]
Beispiel #29
0
class BytesArrayModel(models.Model):
    entries = ArrayField(dbtype="bytea")
Beispiel #30
0
class MultiTypeModel(models.Model):
    smallints = SmallIntegerArrayField()
    varchars = ArrayField(dbtype="varchar(30)")
Beispiel #31
0
class MacAddrModel(models.Model):
    field = ArrayField(dbtype="macaddr", type_cast=str)
Beispiel #32
0
class IntModel(models.Model):
    lista = ArrayField(dbtype='int')
    objects = ExpressionManager()
Beispiel #33
0
 def test_default_formfield_with_choices(self):
     model_field = ArrayField(choices=[('a', 'a')], dbtype='text')
     form_field = model_field.formfield()
     self.assertIsInstance(form_field, forms.TypedMultipleChoiceField)
     self.assertEqual(form_field.choices, [('a', 'a')])
     self.assertEqual(form_field.coerce, force_text)
Beispiel #34
0
class ChoicesModel(models.Model):
    choices = ArrayField(dbtype='text', choices=[('A', 'A'), ('B', 'B')])
Beispiel #35
0
        if self.require_upper and value.upper is None:
            raise ValidationError("Upper datetime bound must be set")
        
    def formfield(self, **kwargs):
        defaults = {'form_class': DateTimeRangeFormField}
        defaults.update(kwargs)
        return super(DateTimeRange, self).formfield(**defaults)


class LowercaseTransform(Transform):
    lookup_name = 'array_lowercase'
    def as_sql(self, qn, connection):
        lhs, params = qn.compile(self.lhs)
        return "array_lowercase(%s)" % (lhs,), params


class SingleContainedByLookup(ContainedByLookup):
    def as_sql(self, qn, connection):
        lhs, lhs_params = self.process_lhs(qn, connection)
        rhs, rhs_params = self.process_rhs(qn, connection)
        params = lhs_params + rhs_params
        return "ARRAY[%s] <@ %s::%s[]" % (lhs, rhs, self.lhs.output_field.db_type(connection)), params


UUIDField.register_lookup(SingleContainedByLookup)
DateTimeRange.register_lookup(ContainedByLookup)
DateTimeRange.register_lookup(ContainsLookup)
DateTimeRange.register_lookup(OverlapLookup)
ArrayField.register_lookup(LowercaseTransform)
NativeArrayField.register_lookup(LowercaseTransform)
Beispiel #36
0
 def test_default_formfield_with_choices(self):
     model_field = ArrayField(choices=[('a', 'a')], dbtype='text')
     form_field = model_field.formfield()
     self.assertIsInstance(form_field, forms.TypedMultipleChoiceField)
     self.assertEqual(form_field.choices, [('a', 'a')])
     self.assertEqual(form_field.coerce, force_text)