class PodHints(CleanSave, Model): """Hint information for a pod.""" class Meta(DefaultMeta): """Needed for South to recognize this model.""" pod = OneToOneField("BMC", related_name="hints", on_delete=CASCADE) nodes = ManyToManyField("Node") cores = IntegerField(default=0) memory = IntegerField(default=0) cpu_speed = IntegerField(default=0) # MHz local_storage = BigIntegerField( # Bytes blank=False, null=False, default=0 ) local_disks = IntegerField(blank=False, null=False, default=-1) iscsi_storage = BigIntegerField( # Bytes blank=False, null=False, default=-1 )
class Info(models.Model): status = BooleanField(default=False) # data mid = BigIntegerField(null=True) name = TextField(null=True) sex = TextField(null=True) rank = BigIntegerField(null=True) face = TextField(null=True) regtime = BigIntegerField(null=True) spacesta = BigIntegerField(null=True) birthday = TextField(null=True) sign = TextField(null=True) toutu = TextField(null=True) toutuId = BigIntegerField(null=True) theme = TextField(null=True) theme_preview = TextField(null=True) coins = BigIntegerField(null=True) im9_sign = TextField(null=True) fans_badge = BooleanField(default=False) # level_info level_info_current_level = BigIntegerField(null=True) # official_verify official_verify_type = BigIntegerField(null=True) official_verify_desc = TextField(null=True) official_verify_suffix = TextField(null=True) # vip vip_vipType = BigIntegerField(null=True) vip_vipStatus = BigIntegerField(null=True) local_recorded_at = DateTimeField(auto_now_add=True)
def prepare_sql(self): if self.query.prepare_statement_sql: return self.query.prepare_statement_sql, self.query.prepare_statement_sql_params sql, params = self.as_sql() name = self._generate_statement_name(sql) arguments = [] fixed_sql_params = [] prepare_params_order = [] for param in params: for prepare_param_hash, prepare_param in self.query.prepare_params_by_hash.items( ): if isinstance(param, str) and prepare_param_hash in param: field = prepare_param.field_type if isinstance(field, BigAutoField): field = BigIntegerField() elif isinstance(field, AutoField): field = IntegerField() arguments.append(field.db_type(self.connection)) prepare_params_order.append(prepare_param_hash) break else: fixed_sql_params.append(param) prepared_operations = PreparedOperationsFactory.create( self.connection.vendor) prepare_statement = prepared_operations.prepare_sql( name=name, arguments=arguments, sql=sql) placeholders = tuple( prepared_operations.prepare_placeholder(i) for i in range(1, len(arguments) + 1)) sql_with_placeholders = prepare_statement.format(*placeholders) self.query.set_prepare_statement_sql(sql_with_placeholders, fixed_sql_params) self.query.set_prepare_params_order(prepare_params_order) return sql_with_placeholders, fixed_sql_params
class Message(Model): """ Contains all public messages """ sender = ForeignKey(User, CASCADE) room = ForeignKey(Room, CASCADE, null=True) # DateField.auto_now time = BigIntegerField(default=get_milliseconds) content = TextField(null=True, blank=True) # if symbol = null - no images refers this row # symbol is the same as "select max(symbol) from images where message_id = message.id # we store symbol in this table in case if user edits message # - images that refers same message always have unique symbols symbol = CharField(null=True, max_length=1, blank=True) deleted = BooleanField(default=False) thread_messages_count = IntegerField(default=0, null=False) parent_message = ForeignKey('self', CASCADE, null=True, blank=True) giphy = URLField(null=True, blank=True) edited_times = BigIntegerField(default=get_milliseconds, null=False) def __unicode__(self): return self.__str__() def __str__(self): if self.content is None: v = '' elif len(self.content) > 50: v = self.content[:50] else: v = self.content v = json.dumps(v) return "{}/{}".format(self.id, v)
class campaign(Model): architecture = TextField() aux = BooleanField() aux_command = TextField(null=True) aux_output = TextField(default=str) aux_output_file = BooleanField(default=False) aux_log_files = ArrayField(TextField(), default=list) checkpoints = IntegerField(null=True) command = TextField(default=str) cycles = BigIntegerField(null=True) cycles_between = BigIntegerField(null=True) debugger_output = TextField(default=str) description = TextField(null=True) dut_output = TextField(default=str) execution_time = FloatField(null=True) kill_dut = BooleanField(default=False) kill_aux = BooleanField(default=False) log_files = ArrayField(TextField(), default=list) output_file = TextField(null=True) rsakey = TextField() simics = BooleanField() caches = BooleanField() start_cycle = BigIntegerField(null=True) start_time = FloatField(null=True) timestamp = DateTimeField(auto_now_add=True)
class Tweet(Model): raw_text = CharField(max_length=512) # Tweepy.models.status.text author_name = CharField(max_length=256) # Tweepy.models.status.author.name author_id = BigIntegerField() # Tweepy.models.status.author.id created_at = DateTimeField() # Tweepy.models.status.created_at (a datetime.datetime object) tweet_id = BigIntegerField() # Tweepy.models.status.id def __str__(self): return self
class Holding(Model): holder = CharField(max_length=4096, db_index=True) source = CharField(max_length=4096, null=True) resource = CharField(max_length=4096, null=False) limit = BigIntegerField() usage_min = BigIntegerField(default=0) usage_max = BigIntegerField(default=0) class Meta: unique_together = (('holder', 'source', 'resource'), )
class RecordingFile(Model): recording = ForeignKey( Recording, CASCADE, related_name='files', related_query_name='file') file_num = IntegerField() start_index = BigIntegerField() length = BigIntegerField() path = CharField(max_length=255, unique=True, null=True) def __str__(self): r = self.recording s = '{} / File {} / duration {:0.3f} h'.format( str(r), self.file_num, self.duration / 3600) if self.path is not None: s += ' / "{}"'.format(self.path) return s class Meta: unique_together = ('recording', 'file_num') db_table = 'vesper_recording_file' @property def end_index(self): return self.start_index + self.length @property def num_channels(self): return self.recording.num_channels @property def sample_rate(self): return self.recording.sample_rate @property def start_time(self): offset = signal_utils.get_duration(self.start_index, self.sample_rate) return self.recording.start_time + datetime.timedelta(seconds=offset) @property def end_time(self): return self.start_time + datetime.timedelta(seconds=self.span) @property def duration(self): return signal_utils.get_duration(self.length, self.sample_rate) @property def span(self): return signal_utils.get_span(self.length, self.sample_rate)
def get_queryset(self): return (super().get_queryset().filter( contracts__available=True, contracts__expires_at__gte=timezone.now()).annotate( contract_price=F('contracts__price'), contract_plex=F('contracts__plex'), contract_price_inc_plex=ExpressionWrapper( Cast('contracts__plex', BigIntegerField()) * Value(4100000, output_field=BigIntegerField()) + F('contracts__price'), output_field=DecimalField()), contract_id=F('contracts__id'), contract_single=F('contracts__single_item'), contract_auction=F('contracts__auction')))
class ProvisionLog(Model): serial = BigIntegerField() name = CharField(max_length=4096) issue_time = CharField(max_length=4096) log_time = CharField(max_length=4096) holder = CharField(max_length=4096) source = CharField(max_length=4096, null=True) resource = CharField(max_length=4096) limit = BigIntegerField() usage_min = BigIntegerField() usage_max = BigIntegerField() delta_quantity = BigIntegerField() reason = CharField(max_length=4096)
class NUMANodeHugepages(CleanSave, TimestampedModel): """Hugepages memory for a numa node.""" numanode = ForeignKey( NUMANode, editable=False, on_delete=CASCADE, related_name="hugepages_set", ) page_size = BigIntegerField() total = BigIntegerField() class Meta: unique_together = [("numanode", "page_size")]
class Example_Trial(models.Model): # Trial Stuff save_time = models.DateTimeField('start date') rt = BigIntegerField(default=0) trial_type = models.CharField(max_length=200,default='NaN') key_press = models.CharField(max_length=200,default='NaN') trial_index = BigIntegerField(default=0) time_elapsed = BigIntegerField(default=0) # participant stuff MID = models.CharField(max_length=200,default='NaN') AID = models.CharField(max_length=200,default='NaN') HID = models.CharField(max_length=200,default='NaN') session_id =models.CharField(max_length=200,default=None)
def __getitem__(self, k): if isinstance(k, slice) and ((k.start is None or isinstance(k.start, (BindParam, int))) or (k.stop is None or isinstance(k.stop, (BindParam, int)))): if k.step: raise PreparedStatementException('Step isn\'t supported!') if isinstance(k.start, BindParam): k.start.field_type = BigIntegerField() if isinstance(k.stop, BindParam): k.stop.field_type = BigIntegerField() k.stop.set_normalize_func( lambda v, values: v - (values.get(k.start.name) if isinstance(k.start, BindParam) else k.start or 0)) qs = self.all() qs.query.set_limits(k.start, k.stop) return qs return super(PreparedQuerySet, self).__getitem__(k) # pragma: no cover
def get_field_db_type(field, conn): # type: (models.Field, ConnectionProxy) -> str """ Get database field type used for this field. :param field: django.db.models.Field instance :param conn: Database connection used :return: Database type name (str) """ # db_type() as id field returned 'serial' instead of 'integer' here # rel_db_type() return integer, but it is not available before django 1.10 # rel_db_type() returns serial[] for arrays. # cast_db_type() is not well documented and returns serial too. db_type = field.db_type(conn) # Some external libraries may add column fields here # Let's cut them cut_phrases = [ 'CONSTRAINT', 'NOT NULL', 'NULL', 'CHECK', 'DEFAULT', 'UNIQUE', 'PRIMARY KEY', 'REFERENCES', 'COLLATE' ] for ph in cut_phrases: db_type = db_type.split(ph, 1)[0] db_type = db_type.strip() if 'bigserial' in db_type: db_type = db_type.replace('bigserial', BigIntegerField().db_type(conn)) elif 'serial' in db_type: db_type = db_type.replace('serial', IntegerField().db_type(conn)) return db_type
class TestModelFields(Model): big_int = BigIntegerField() yesno = BooleanField() title = CharField(max_length=150) csv_data = CommaSeparatedIntegerField(max_length=255) when = DateField() when_accurate = DateTimeField() amount = DecimalField(max_digits=8, decimal_places=4) email = EmailField() upload = FileField(upload_to='test') path = FilePathField(path=d.APP_DIR, recursive=False, match=".json$") inaccurate = FloatField() img = ImageField(upload_to='test') ip = IPAddressField() better_ip = GenericIPAddressField(protocol='both') yesnomaybe = NullBooleanField(default=None) posint = PositiveIntegerField() small_posint = PositiveSmallIntegerField() slug = SlugField() small_int = SmallIntegerField() content = TextField() when_time = TimeField() web_address = URLField() user = ForeignKey('auth.User') groups = ManyToManyField('auth.Group') one_to_one = OneToOneField('auth.Permission') class Meta: verbose_name = 'test model fields' verbose_name_plural = 'test model fields'
def get_tweets_for_column(social_column, since_id=None, max_id=None, startIndex=None, stopIndex=None, limit=None): queryset = Tweets.objects.annotate( tweet_id_bigint=Cast("tweet_id", BigIntegerField())) if since_id is not None: queryset = queryset.filter(tweet_id_bigint__gt=since_id) if max_id is not None: queryset = queryset.filter(tweet_id_bigint__lte=max_id) if since_id is not None and max_id is not None and since_id >= max_id: logger.warning( "since_id {} is out of range of max_id {} in get_tweets_for_column - it should be a lower number!" ) return None queryset = apply_tweet_filter_criteria(social_column, queryset) tweets = queryset.order_by("-tweet_id_bigint").values() if limit is not None: return tweets[:int(limit)] elif startIndex is not None and stopIndex is not None: # FIXME Work out why the very end of a column is not returning the last tweet. Add +1 for now to hackily work around it. # logger.info("col {}: startIndex = {}, stopIndex = {}, len = {}".format(social_column.id, startIndex, stopIndex, len(t))) return tweets[int(startIndex):int(stopIndex) + 1] else: return tweets
class PodStoragePool(CleanSave, Model): """Storage pool for a pod.""" class Meta(DefaultMeta): """Needed for South to recognize this model.""" pod = ForeignKey( "BMC", blank=False, null=False, related_name="storage_pools", on_delete=CASCADE, ) name = CharField(max_length=255, null=False, blank=False) pool_id = CharField(max_length=255, null=False, blank=False) pool_type = CharField(max_length=255, null=False, blank=False) path = CharField(max_length=4095, null=False, blank=False) storage = BigIntegerField(blank=False, null=False, default=0) # Bytes def get_used_storage(self): """Calculate the used storage for this pod.""" from maasserver.models.virtualmachine import VirtualMachineDisk count = VirtualMachineDisk.objects.filter( vm__project=self.pod.tracked_project, backing_pool=self, ).aggregate(used=Coalesce(Sum("size"), Value(0))) return count["used"]
class OToolkitHOTPDevice(OToolkitDevice): """ HOTP-based django-otp_ ``Device``, using :mod:`oath_toolkit`. .. _django-otp: https://pypi.python.org/pypi/django-otp .. attribute:: counter The current position of the event counter. Upon each successful token verification, it increments by one. Defaults to ``0``. :type: :class:`django.db.models.BigIntegerField` """ select_name = __(u'HMAC-based OTP (HOTP) generator') oath_type = b'hotp' counter = BigIntegerField(default=0) class Meta: verbose_name = u'OATH Toolkit HOTP Device' def verify_token(self, token): verified = self._do_verify_token(token, self.oath.hotp_validate, self.counter) if verified is not False: self.counter = F('counter') + verified.relative + 1 self.save() # Update the counter value in this instance self.counter = self.__class__.objects.get(pk=self.pk).counter verified = True return verified
class DetailsList(models.Model): class Meta: verbose_name = ' جزئیات لیست ' verbose_name_plural = ' جزئیات لیست ' month_list = models.ForeignKey('MonthList', on_delete=models.CASCADE, verbose_name='لیست ماهانه') worker = models.ForeignKey('Workers', on_delete=models.CASCADE, verbose_name=' نام کارگر') working_days = models.SmallIntegerField('تعداد روز کارکرد') daily_wage = models.BigIntegerField('دستمزد روزانه') advantage = models.BigIntegerField('مزایای ماهانه') start_date = models.CharField('تاریخ شروع به کار ', null=True, max_length=8) end_date = models.CharField('تاریخ پایان به کار ', null=True, max_length=8) _monthly_wage = None objects = AnnotationManager(monthly_wage=ExpressionWrapper( F('working_days') * F('daily_wage'), output_field=BigIntegerField())) def __str__(self): return '{} {} {} '.format(self.worker.FirstName, self.worker.LastName, self.month_list)
class PodStoragePool(CleanSave, Model): """Storage pool for a pod.""" class Meta(DefaultMeta): """Needed for South to recognize this model.""" pod = ForeignKey( "BMC", blank=False, null=False, related_name="storage_pools", on_delete=CASCADE, ) name = CharField(max_length=255, null=False, blank=False) pool_id = CharField(max_length=255, null=False, blank=False) pool_type = CharField(max_length=255, null=False, blank=False) path = CharField(max_length=4095, null=False, blank=False) storage = BigIntegerField(blank=False, null=False, default=0) # Bytes def get_used_storage(self): """Calculate the used storage for this pod.""" # Circular import. from maasserver.models.physicalblockdevice import PhysicalBlockDevice query = PhysicalBlockDevice.objects.filter(storage_pool=self) query = query.aggregate(size=Sum("size")) size = query["size"] if size is None: size = 0 return size
class VirtualMachineDisk(CleanSave, TimestampedModel): """A disk attached to a virtual machine.""" class Meta(DefaultMeta): unique_together = ("vm", "name") name = CharField(max_length=255, blank=False) vm = ForeignKey( VirtualMachine, editable=False, on_delete=CASCADE, related_name="disks_set", ) backing_pool = ForeignKey( PodStoragePool, editable=False, null=True, on_delete=CASCADE, related_name="vmdisks_set", ) block_device = OneToOneField( BlockDevice, on_delete=SET_NULL, default=None, blank=True, null=True, editable=False, related_name="vmdisk", ) size = BigIntegerField()
def test_bigforeignkey_db_type(self, make_bigint, make_bigtosmall): make_bigint() make_bigint() make_bigtosmall() make_bigtosmall() qs = BigIntModel.objects.recently_updated() # クエリがデータを返すかどうかをチェック assert qs for obj in qs: for f in obj._meta.fields: if f.name == "big_id_obj": db_type = f.db_type(connection) bigint_type = BigIntegerField().db_type(connection=connection) assert db_type == bigint_type # oracleでは動かない qs = BigToSmallModel.objects.recently_updated() # クエリがデータを返すかどうかをチェック assert qs for obj in qs: for f in obj._meta.fields: if f.name == "small_id_obj": db_type = f.db_type(connection) int_type = IntegerField().db_type(connection=connection) assert db_type == int_type # oracleでは動かない
class Anime(models.Model): anime_id = models.AutoField(primary_key=True, editable =False) name = CharField(max_length = 100) genre = CharField(max_length = 200) MOVIE = "Movie" TV = "TV" OVA = "OVA" ONA = "ONA" SPECIAL = "Special" GENRE_CHOICE = ( (MOVIE, "Movie"), (TV, "TV"), (OVA, "OVA"), (ONA, "ONA"), (SPECIAL, "Special") ) anime_type = CharField( max_length = 7, choices = GENRE_CHOICE, default = TV, ) episodes = IntegerField() rating = FloatField(validators=[MinValueValidator(0.0), MaxValueValidator(10)], default = 0) members = BigIntegerField() anime_photo = ImageField(null = True, upload_to = 'img/profiles', verbose_name = "Anime Photo", default = "{% static 'img/placeholder.jpg' %}") class Meta: ordering = ('-rating',)
class Trial(models.Model): PID = models.CharField(max_length=200) trial_number = models.CharField(max_length=200) # Timing Stuff start_date = models.DateTimeField('start date') trialstart = BigIntegerField() # Outcomes correct_choice = IntegerField() # (1=green) outcome = IntegerField() chosen_mag = IntegerField() green_reward = IntegerField() blue_reward = IntegerField() reaction_time = IntegerField() # left_stimuli = models.CharField(max_length=200) right_stimuli = models.CharField(max_length=200) # totalpoints = models.IntegerField(null=True)
def annotate_typed_pk(self): cast_field = self.model._meta.pk if isinstance(cast_field, BigAutoField): cast_field = BigIntegerField() elif isinstance(cast_field, AutoField): cast_field = IntegerField() return self.annotate(typed_pk=Cast('object_id', cast_field))
class Order(ConcurrentTransitionMixin, Model): class Meta: app_label = APP_LABEL abstract = True NEW = STATE.NEW PROCESSING = STATE.PROCESSING PROCESSED = STATE.PROCESSED ERROR = STATE.ERROR CHOICES = STATE.CHOICES id = BigIntegerField(primary_key=True, editable=False) email = EmailField() first_name = CharField(max_length=254) last_name = CharField(max_length=254) received = DateTimeField(default=timezone.now) status = FSMIntegerField(choices=CHOICES, default=NEW, protected=True) @transition(field=status, source=NEW, target=PROCESSING, on_error=ERROR) def start_processing(self): logger.debug('Processing order %s' % self.id) @transition(field=status, source=PROCESSING, target=PROCESSED, on_error=ERROR) def finish_processing(self): logger.debug('Finishing order %s' % self.id) @transition(field=status, source=PROCESSING, target=ERROR) def fail(self): logger.debug('Failed to process order %s' % self.id)
def _handle_pk_field(queryset): pk = queryset.model._meta.pk if isinstance(pk, ForeignKey): return _handle_pk_field(pk.target_field) if isinstance( pk, ( IntegerField, AutoField, BigIntegerField, PositiveIntegerField, PositiveSmallIntegerField, SmallIntegerField, ), ): return partial(Cast, output_field=BigIntegerField()) if isinstance(pk, UUIDField): if connection.features.has_native_uuid_field: return partial(Cast, output_field=UUIDField()) return partial( Replace, text=Value('-'), replacement=Value(''), output_field=CharField(), ) return None
class TweetBase(Model): """ We don't need: in_reply_to_status_id_str id_str in_reply_to_user_id_str """ _id = AutoField(primary_key=True, db_column='id') source = CharField(max_length=255) # we don't need entities = 1 geo = 1 in_reply_to_user_id = PositiveIntegerField(null=True, blank=True) text = CharField(max_length=255) id = BigIntegerField(db_column='tweet_id') in_reply_to_status_id = BigIntegerField(null=True, blank=True) created_at = DateTimeField() in_reply_to_screen_name = CharField(max_length=15) retweeted_status = OneToOneField('self', null=True, blank=True) objects = TweetQuerySet.as_manager() def __str__(self): return self.text def get_entities_class(self): raise NotImplementedError("Concrete subclasses should implement this") @property def entities(self): # should prolly cache this ... cls = self.get_entities_class() return cls( user_mentions=self.entity_mention_set.all(), media=self.entity_media_set.all(), hashtags=self.entity_hashtags_set.all(), urls=self.entity_urls_set.all(), ) def parse(self): parser = ttp.Parser() return parser.parse(self.text) def text_as_html(self): return self.parse().html class Meta: abstract = True
class Patient(models.Model): """Defines a patient.""" opendental_patient_id = BigIntegerField(primary_key=True, default=0) user = ForeignKey(User, on_delete=models.CASCADE) ssn = USSocialSecurityNumberField(unique=True) first_name = CharField(max_length=100) last_name = CharField(max_length=100)
class MouseEvent(ExtraModel): #player = models.Link(MouseTrackingPlayer) #player = ForeignKey('mousetracking.Player') player = models.Link('mousetracking.Player') stimulus = models.StringField() region = models.IntegerField() action = models.StringField() timestamp = BigIntegerField()