class OCPCostSummaryByNode(models.Model): """A MATERIALIZED VIEW specifically for UI API queries. This table gives a daily breakdown of compute usage. """ class Meta: """Meta for OCPCostSummary.""" db_table = "reporting_ocp_cost_summary_by_node" managed = False id = models.IntegerField(primary_key=True) cluster_id = models.TextField() cluster_alias = models.TextField(null=True) node = models.CharField(max_length=253, null=False) usage_start = models.DateField(null=False) usage_end = models.DateField(null=False) infrastructure_raw_cost = models.DecimalField(max_digits=33, decimal_places=15, null=True) infrastructure_usage_cost = JSONField(null=True) infrastructure_markup_cost = models.DecimalField(max_digits=33, decimal_places=15, null=True) infrastructure_monthly_cost = models.DecimalField(max_digits=33, decimal_places=15, null=True) supplementary_usage_cost = JSONField(null=True) supplementary_monthly_cost = models.DecimalField(max_digits=33, decimal_places=15, null=True) source_uuid = models.UUIDField(unique=False, null=True)
class Transaction(models.Model): """Represents a single payment operation. Transaction is an attempt to transfer money between your store and your customers, with a chosen payment method. """ created = models.DateTimeField(auto_now_add=True, editable=False) payment = models.ForeignKey(Payment, related_name="transactions", on_delete=models.PROTECT) token = models.CharField(max_length=512, blank=True, default="") kind = models.CharField(max_length=25, choices=TransactionKind.CHOICES) is_success = models.BooleanField(default=False) action_required = models.BooleanField(default=False) action_required_data = JSONField(blank=True, default=dict, encoder=DjangoJSONEncoder) currency = models.CharField( max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH) amount = models.DecimalField( max_digits=settings.DEFAULT_MAX_DIGITS, decimal_places=settings.DEFAULT_DECIMAL_PLACES, default=Decimal("0.0"), ) error = models.CharField( max_length=256, null=True, ) customer_id = models.CharField(max_length=256, null=True) gateway_response = JSONField(encoder=DjangoJSONEncoder) already_processed = models.BooleanField(default=False) class Meta: ordering = ("pk", ) def __repr__(self): return "Transaction(type=%s, is_success=%s, created=%s)" % ( self.kind, self.is_success, self.created, ) def get_amount(self): return Money(self.amount, self.currency)
class ActionLog(UUIDPrimary): content_type = models.ForeignKey( "contenttypes.ContentType", related_name="+", verbose_name=_("content type"), blank=True, null=True, on_delete=models.PROTECT, ) object_pk = models.CharField( verbose_name=_("object pk"), max_length=255, blank=True, null=True, db_index=True, ) user = models.ForeignKey( get_user_model(), verbose_name=_("user"), blank=True, null=True, on_delete=models.PROTECT, related_name="actionlogs", ) template_name = models.CharField(max_length=255, blank=False, null=False) template_data = JSONField( verbose_name=_("template rendering data"), blank=True, null=True ) changes = JSONField(blank=True, verbose_name=_("change diff")) remote_ip = models.GenericIPAddressField( verbose_name=_("remote IP"), blank=True, null=True ) created_at = models.DateTimeField(verbose_name=_("created at"), auto_now_add=True) class Meta: ordering = ["-created_at"] verbose_name = _("log action") verbose_name_plural = _("log actions") def __str__(self): return _("Logged action, id: {id}").format(id=self.id) def get_edited_object(self): """Returns the edited object represented by this log entry""" return self.content_type.get_object_for_this_type(pk=self.object_pk)
class Model(models.Model): pickle_path = models.TextField() project = models.ForeignKey("Project", on_delete=models.CASCADE) training_set = models.ForeignKey("TrainingSet", on_delete=models.CASCADE) cv_accuracy = models.FloatField() cv_metrics = JSONField() predictions = models.ManyToManyField( "Data", related_name="models", through="DataPrediction" )
class Profile(Model): meta = JSONField(default = dict, null = True, blank = True) user = AutoOneToOneField(User,on_delete=CASCADE) countries = ManyToManyField(Country,related_name="assignees") waiver = BooleanField(default = False) def __str__(self): return f"profile of {self.user.username}" # pylint: disable=no-member
class Linkaja(BaseModelGeneric): transaction_status = models.CharField(choices=PAYMENT_STATUSES, max_length=40) transaction_id = models.CharField(max_length=40, blank=True, null=True) transaction_date = models.CharField(max_length=40, blank=True, null=True) amount = models.DecimalField(default=0, decimal_places=2, max_digits=12) payload = JSONField(blank=True, null=True) responses = JSONField(blank=True, null=True) checkout_url = models.TextField() phone_number = models.CharField(max_length=40) def __str__(self): return "%s : %s <%s>" % (self.created_by, self.amount, self.transaction_status) class Meta: verbose_name = _("Linkaja") verbose_name_plural = _("Linkaja")
class EntailmentType(base.IrekuaModelBase): source_type = models.ForeignKey( 'TermType', related_name='entailment_source_type', db_column='source_type_id', verbose_name=_('source type'), help_text=_('Term type of source of entailment'), on_delete=models.CASCADE, blank=False, null=False) target_type = models.ForeignKey( 'TermType', related_name='entailment_target_type', db_column='target_type_id', verbose_name=_('target type'), help_text=_('Term type of target of entailment'), on_delete=models.CASCADE, blank=False, null=False) metadata_schema = JSONField( db_column='metadata_schema', verbose_name=_('metadata schema'), help_text=_('JSON Schema for metadata of entailment info'), blank=True, null=False, default=simple_JSON_schema, validators=[validate_JSON_schema]) class Meta: verbose_name = _('Entailment Type') verbose_name_plural = _('Entailment Types') unique_together = (('source_type', 'target_type')) ordering = ['source_type'] def __str__(self): msg = '%(source_type)s => %(target_type)s' params = dict(source_type=str(self.source_type), target_type=str(self.target_type)) return msg % params def clean(self): if self.source_type == self.target_type: msg = _( 'Entailments are not possible between terms of the same type') raise ValidationError({'target': msg}) def validate_metadata(self, metadata): try: validate_JSON_instance(schema=self.metadata_schema, instance=metadata) except ValidationError as error: msg = _( 'Invalid metadata for entailment between terms of types %(entailment)s. Error: %(error)s' ) params = dict(entailment=str(self), error=str(error)) raise ValidationError(msg, params=params)
class Game(Model): name = CharField(max_length=255) state = JSONField() last_card = CharField(max_length=2, null=True) active_player = IntegerField() p1_code = CharField(max_length=255, null=True) p2_code = CharField(max_length=255, null=True) p1_name = CharField(max_length=255, null=True) p2_name = CharField(max_length=255, null=True)
class Product(models.Model): name = CharField(max_length=100, default="Unknown") attributes = JSONField() price = DecimalField(max_digits=10, decimal_places=2) class Meta: db_table = "products" # -price for descending ordering ordering = ['-price']
class Order(Model): model_name = 'Order' id: int = AutoField(primary_key=True) original_id: str = CharField('Original Id', max_length=255, null=True) cost: int = PositiveIntegerField('Cost') idempotency_token: str = CharField('Idempotency Token', max_length=255, null=True) terminal: Optional[Terminal] = ForeignKey(to=Terminal, on_delete=PROTECT) items: Dict = JSONField('Items', default=dict) description: str = CharField('Description', max_length=255, null=True) tpaga_transaction: Dict = JSONField('Tpaga Transaction', default=dict) created_at: datetime = DateTimeField('Created At', auto_now_add=True, db_index=True) updated_at: datetime = DateTimeField('Updated At', auto_now=True)
class SubmitConfig(models.Model): """ This is an abstract model providing JSONField to store submit configurations. """ configuration = JSONField(default=dict) class Meta: abstract = True
class Provider(models.Model): def get_absolute_url(self): return "/settings/" user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) type = models.CharField(max_length=255) config = JSONField() def __str__(self): return self.name
class Menu(models.Model): name = models.CharField(max_length=128, choices=settings.DEFAULT_MENUS.items(), unique=True) json_content = JSONField(blank=True, default=dict, editable=False) class Meta: ordering = ("pk",) def __str__(self): return self.name
class Table(Labelled): """Collection of Columns.""" base_model = models.ForeignKey(ContentType, verbose_name=_("Base model"), on_delete=models.CASCADE) sort_option = models.IntegerField( default=0, verbose_name=_("Sort option"), choices=[(x.id, format_lazy("{label} - {text}", label=x.label, text=x.help_text)) for x in AllSortOptions.values()], ) attrs = JSONField(verbose_name=_("HTML attributes"), blank=True, null=True) group_prefix = models.CharField( verbose_name=_("Group prefix"), null=True, blank=True, max_length=200, help_text=_("""this value is used as a prefix only when "Sort option" is set to "sort in group" """), ) empty_template = models.TextField( verbose_name=_("Empty template"), null=True, blank=True, help_text=_(""" Template which will be displayed when there is no data for this table. """), default=_("There is no data for this table."), ) class Meta: verbose_name = _("Table") verbose_name_plural = _("Tables") def clean(self): if self.sort_option == SortInGroup.id: if not self.group_prefix: raise ValidationError({ "group_prefix": [ ValidationError( _("Please enter group prefix if you want to sort in " "group")) ] }) def get_prefix(self): return AllSortOptions[self.sort_option].get_prefix(None, self)
class Migration(migrations.Migration): dependencies = [ ('terra_geocrud', '0005_auto_20190724_1435'), ] operations = [ migrations.AddField( model_name='crudview', name='settings', field=JSONField(blank=True, default=dict), ), migrations.AddField( model_name='crudview', name='ui_schema', field=JSONField(blank=True, default=dict), ), ]
class NotificationActionTask(ActionTask): default_data = JSONField( default=dict, blank=True, help_text='The data required for the notification task to function. ' 'Normally API details or similar') def __str__(self): return self.name
class BaseBillingEntity(LiveModel): company = models.CharField(max_length=128, blank=True, null=True) address_1 = models.CharField(max_length=128) address_2 = models.CharField(max_length=128, blank=True, null=True) country = models.CharField(choices=countries, max_length=3) phone = models.CharField(max_length=32, blank=True, null=True) email = models.CharField(blank=True, null=True, max_length=254) city = models.CharField(max_length=128) state = models.CharField(max_length=128, blank=True, null=True) zip_code = models.CharField(max_length=32, blank=True, null=True) extra = models.TextField( blank=True, null=True, help_text='Extra information to display on the invoice ' '(markdown formatted).') meta = JSONField(blank=True, null=True, default=dict, encoder=DjangoJSONEncoder) class Meta: abstract = True @property def billing_name(self): return self.company or self.name @property def slug(self): return slugify(self.billing_name) def address(self): return ", ".join([ _f for _f in [ self.address_1, self.city, self.state, self.zip_code, self.country ] if _f ]) address.short_description = 'Address' def get_list_display_fields(self): field_names = [ 'company', 'email', 'address_1', 'city', 'country', 'zip_code' ] return [getattr(self, field, '') for field in field_names] def get_archivable_field_values(self): field_names = [ 'company', 'email', 'address_1', 'address_2', 'city', 'country', 'city', 'state', 'zip_code', 'extra', 'meta' ] return {field: getattr(self, field, '') for field in field_names} def __str__(self): return (u'%s (%s)' % (self.name, self.company) if self.company else self.name)
class Tunnel(models.Model): name = models.CharField(max_length=20) partA = models.ForeignKey('PatchFieldPort', on_delete=models.CASCADE, related_name='partA') partB = models.ForeignKey('PatchFieldPort', on_delete=models.CASCADE, related_name='partB') data = JSONField()
class JSONBAgg(OrderableAggMixin, Aggregate): function = 'JSONB_AGG' template = '%(function)s(%(expressions)s %(ordering)s)' output_field = JSONField() def convert_value(self, value, expression, connection): if not value: return '[]' return value
class Rooms(Model): player = ForeignKey(CustomUser, on_delete=CASCADE) game = ForeignKey("Game", on_delete=CASCADE) player_cards = JSONField() has_left = BooleanField(default=False) winner = BooleanField(default=False) def __str__(self): return f"Player = {self.player} Cards = {self.player_cards} Left = {self.has_left} Win = {self.winner}"
class FunctionProblem(Problem): """Problem that requires a function definition as solution""" # IMPORTANT: This problem does not support multiple initial db. It only uses the first db check_order = models.BooleanField(default=False) solution = models.TextField(max_length=5000, validators=[MinLengthValidator(1)], blank=True) calls = models.TextField(max_length=5000, validators=[MinLengthValidator(1)], default='', blank=True) expected_result = JSONField(encoder=DjangoJSONEncoder, blank=True) class Meta: """ Changes the name displayed in the admin interface""" verbose_name_plural = 'Problem_Function' def clean(self): """Executes the problem and stores the expected result""" try: if self.zipfile: # Replaces the fields with the information from the file load_function_problem(self, self.zipfile) self.zipfile = None # Avoids storing the file in the filesystem super().clean() executor = OracleExecutor.get() res = executor.execute_function_test(self.create_sql, self.insert_sql, self.solution, self.calls) self.expected_result = [res['results']] self.initial_db = [res['db']] except Exception as excp: raise ValidationError(excp) from excp def template(self): return 'problem_function.html' def result_as_table(self): """Transforms the dict with the expected result in a dict representing a table that can be shown in the templates (i.e., we add a suitable header and create rows)""" rows = [[call, result] for call, result in self.expected_result[0].items()] return { 'rows': rows, 'header': [('Llamada', None), ('Resultado', None)] } def judge(self, code, executor): oracle_result = executor.execute_function_test(self.create_sql, self.insert_sql, code, self.calls) return compare_function_results(self.expected_result[0], oracle_result['results']) def problem_type(self): return ProblemType.FUNCTION
class PredefinedFilter(models.Model): name = models.CharField(_('naam'), max_length=255) args = JSONField(_('instellingen'), default=dict, blank=True) def __str__(self): return str(self.name) class Meta: verbose_name = _('Voorgedefinieerde filter')
class Migration(migrations.Migration): dependencies = [ ('invoicing', '0025_supplier_additional_info_json'), ] operations = [ migrations.AlterField( model_name='invoice', name='attachments', field=JSONField(blank=True, default=None, null=True), ), migrations.AlterField( model_name='invoice', name='supplier_additional_info', field=JSONField(blank=True, default=None, null=True), ), ]
class OCPVolumeSummary(models.Model): """A MATERIALIZED VIEW specifically for UI API queries. This table gives a daily breakdown of compute usage. """ class Meta: """Meta for OCPVolumeSummary.""" db_table = "reporting_ocp_volume_summary" managed = False id = models.IntegerField(primary_key=True) cluster_id = models.TextField() cluster_alias = models.TextField(null=True) resource_ids = ArrayField(models.CharField(max_length=256), null=True) resource_count = models.IntegerField(null=True) data_source = models.CharField(max_length=64, null=True) usage_start = models.DateField(null=False) usage_end = models.DateField(null=False) supplementary_usage_cost = JSONField(null=True) infrastructure_raw_cost = models.DecimalField(max_digits=33, decimal_places=15, null=True) infrastructure_usage_cost = JSONField(null=True) infrastructure_markup_cost = models.DecimalField(max_digits=33, decimal_places=15, null=True) persistentvolumeclaim_usage_gigabyte_months = models.DecimalField(max_digits=73, decimal_places=9, null=True) volume_request_storage_gigabyte_months = models.DecimalField(max_digits=73, decimal_places=9, null=True) persistentvolumeclaim_capacity_gigabyte_months = models.DecimalField(max_digits=73, decimal_places=9, null=True) source_uuid = models.UUIDField(unique=False, null=True)
class Prediction(models.Model): """ ML backend predictions """ result = JSONField('result', null=True, default=dict, help_text='Prediction result') score = models.FloatField(_('score'), default=None, help_text='Prediction score', null=True) model_version = models.TextField(_('model version'), default='', blank=True, null=True) cluster = models.IntegerField( _('cluster'), default=None, help_text='Cluster for the current prediction', null=True) neighbors = JSONField( 'neighbors', null=True, blank=True, help_text='Array of task IDs of the closest neighbors') mislabeling = models.FloatField(_('mislabeling'), default=0.0, help_text='Related task mislabeling score') task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, related_name='predictions') created_at = models.DateTimeField(_('created at'), auto_now_add=True) updated_at = models.DateTimeField(_('updated at'), auto_now=True) def created_ago(self): """ Humanize date """ return timesince(self.created_at) def has_permission(self, user): return self.task.project.has_permission(user) class Meta: db_table = 'prediction'
class ModelWithMetadata(models.Model): private_metadata = JSONField(blank=True, null=True, default=dict, encoder=CustomJsonEncoder) metadata = JSONField(blank=True, null=True, default=dict, encoder=CustomJsonEncoder) class Meta: abstract = True def get_value_from_private_metadata(self, key: str, default: Any = None) -> Any: return self.private_metadata.get(key, default) def store_value_in_private_metadata(self, items: dict): if not self.private_metadata: self.private_metadata = {} self.private_metadata.update(items) def clear_private_metadata(self): self.private_metadata = {} def delete_value_from_private_metadata(self, key: str): if key in self.private_metadata: del self.private_metadata[key] def get_value_from_metadata(self, key: str, default: Any = None) -> Any: return self.metadata.get(key, default) def store_value_in_metadata(self, items: dict): if not self.metadata: self.metadata = {} self.metadata.update(items) def clear_metadata(self): self.metadata = {} def delete_value_from_metadata(self, key: str): if key in self.metadata: del self.metadata[key]
class Vacancy(WhoIdMixin, BaseModel): """ Модель вакансии """ def __init__(self, *args, **kwargs): """ Добавление свойства. контекста обекта. """ super().__init__(*args, **kwargs) self.context = {} recruiter = models.ForeignKey(get_user_model(), on_delete=models.PROTECT, related_name='recruiter', related_query_name='recruiter') status = models.CharField('Статус', choices=VACANCY_STATUSES, default=VACANCY_STATUS_NEW, max_length=100) title = models.CharField('Название вакансии', max_length=1000) description = models.TextField('Описание вакансии', max_length=10000) salary = models.CharField('Зарплата', max_length=100) location = models.CharField('Локация', max_length=1000) description_file = models.CharField('Логотип', max_length=1000, blank=True, null=True) skills = JSONField("Требуемы навыки", blank=True, default=dict) reject_reasons = JSONField("Причины блокировки", blank=True, default=dict) responders = models.ManyToManyField(get_user_model(), through='VacancyRespond', through_fields=('vacancy', 'account'), related_name='responders', related_query_name='responders') @property def status_human(self): """ Человекочитаемы статус. :return: """ return VACANCY_STATUSES_DICT[self.status]
class HMCExperiment(Experiment): """Class for associating HMC runs with graphs.""" graph = models.ForeignKey("graph.Graph", on_delete=models.CASCADE, help_text=r"Foreign Key to `graph`") beta = models.DecimalField( null=False, max_digits=10, decimal_places=6, help_text="Inverse temperature, 0 to 9999.999999", ) thermalization_steps = models.PositiveIntegerField( null=False, help_text= "Number of thermalization steps before measuring trajectories.", ) evolution_steps = models.PositiveIntegerField( null=False, help_text="Number of evolution steps when used in measurement.", ) shift_c = models.DecimalField( null=False, max_digits=10, decimal_places=6, help_text="???, 0 to 9999.999999", ) trajectory_length = models.DecimalField( null=False, max_digits=10, decimal_places=6, help_text="???, 0 to 9999.999999", ) md_steps = models.PositiveIntegerField( null=False, help_text="Number of molecular dynamics steps.", ) misc = JSONField( help_text="Dump field for future data. Should be a python dict.") class Meta: constraints = [ models.UniqueConstraint( fields=[ "graph", "beta", "thermalization_steps", "evolution_steps", "shift_c", "trajectory_length", "md_steps", ], name="unique_hmc_run", ) ]
class ResolvableObject(models.Model): id = models.CharField(max_length=200, primary_key=True, serialize=False) data = JSONField() type = models.CharField(max_length=200) dataset = models.ForeignKey(Dataset, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) deleted_date = models.DateField(null=True, blank=True) class Meta: indexes = [GinIndex(fields=['data'])]
class UserRequest(models.Model): time = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) post = JSONField(default=dict) request_type = models.CharField(max_length=20, choices=request_types, default=REQUEST_SIGN_IN) def __str__(self): return f"{self.user} | {self.time}"