Пример #1
0
class Task(models.Model):
    '''
    A stage contains one or more tasks, e.g. payment, upload proposal, etc.
    '''
    stage = models.ForeignKey(to=Stage, related_name='tasks', on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    category = models.ForeignKey(to=TaskCategory, related_name='tasks', on_delete=models.PROTECT)
    widget = models.ForeignKey(to=TaskWidget, related_name='tasks', on_delete=models.PROTECT)
    widget_parameters = jsonfield.JSONField(null=True)
    requires_validation = models.BooleanField(default=False)
    is_user_task = models.BooleanField(default=False)

    def __str__(self):
        return '{} - {}'.format(self.stage.competition.name, self.name)
Пример #2
0
class Node(models.Model):
    id = models.IntegerField(primary_key=True, verbose_name=_('nodeId'))
    name = models.CharField(max_length=30, verbose_name=_('nodeName'))
    imageName = models.CharField(max_length=50, verbose_name=_('imageName'))
    status = models.CharField(max_length=15, verbose_name=_('status'))
    serviceId = models.IntegerField(verbose_name=_('serviceId'))
    createTime = models.CharField(max_length=70, verbose_name=_('createTime'))
    containers = jsonfield.JSONField(verbose_name=_('containers'))

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['id']
Пример #3
0
class Grant(ValidatingModel, models.Model):
    """
    A parameterized membership between a sub-role and super-role.
    The parameters applied to the super-role are all those.
    """

    # Database Fields
    # ---------------

    from_role = models.ForeignKey(
        'Role',
        help_text='The sub-role begin granted membership or permission',
        related_name='memberships_granted',
        on_delete=models.CASCADE,
    )

    to_role = models.ForeignKey(
        'Role',
        help_text='The super-role or permission being given',
        related_name='members',
        on_delete=models.CASCADE,
    )

    assignment = jsonfield.JSONField(
        help_text='Assignment from parameters (strings) to values (any JSON-compatible value)',
        blank=True,
        default=dict,
    )

    class Meta:
        app_label = 'django_prbac'

    # Methods
    # -------

    def instantiated_to_role(self, assignment):
        """
        Returns the super-role instantiated with the parameters of the membership
        composed with the `parameters` passed in.
        """
        composed_assignment = {}
        if assignment:
            for key in self.to_role.parameters & set(assignment.keys()):
                composed_assignment[key] = assignment[key]
        if self.assignment:
            composed_assignment.update(self.assignment)
        return self.to_role.instantiate(composed_assignment)

    def __repr__(self):
        return 'Grant(from_role=%r, to_role=%r, assignment=%r)' % (self.from_role, self.to_role, self.assignment)
Пример #4
0
class Analysis(Titled, UUID, Dated, Shareable):
    sub_processor = models.ForeignKey(SubProcessor,
                                      related_name="analysis",
                                      verbose_name=_('sub_processor'),
                                      blank=False)
    preset = models.ForeignKey(Preset,
                               related_name="analysis",
                               verbose_name=_('preset'),
                               blank=False)
    parameters_schema = jsonfield.JSONField(default=DEFAULT_SCHEMA())

    class Meta:
        verbose_name = _('Analysis')
        verbose_name_plural = _('Analyses')
Пример #5
0
class Broadcast(models.Model):
    domain = models.CharField(max_length=126, db_index=True)
    name = models.CharField(max_length=1000)
    last_sent_timestamp = models.DateTimeField(null=True)
    deleted = models.BooleanField(default=False)

    # A List of [recipient_type, recipient_id]
    recipients = jsonfield.JSONField(default=list)

    class Meta(object):
        abstract = True

    def soft_delete(self):
        raise NotImplementedError()
Пример #6
0
class Report(models.Model):
    name = models.CharField(max_length=200)
    json = jsonfield.JSONField({})
    master = models.IntegerField(null=False, blank=False, unique=True)
    created_at = models.DateTimeField(
        now(),
        editable=False,
        null=True
    )
    updated_at = models.DateTimeField(
        now(),
        editable=False,
        null=True
    )
Пример #7
0
class SimulationElement(models.Model):
    """
    Track result files uploaded to Central
    """
    simulation = models.ForeignKey('SimulationDemand',
                                   related_name='simulation_elements',
                                   on_delete=models.CASCADE)
    timestamp = models.DateTimeField(blank=False, null=False)
    idx = models.IntegerField(blank=False, null=False)
    json_data = jsonfield.JSONField()

    def __str__(self):
        return u'%d: %s, %d, %s, %s' % (self.pk, self.simulation, self.idx,
                                        self.timestamp, self.json_data)
Пример #8
0
class Url(models.Model):
    city = models.ForeignKey('City',
                             on_delete=models.CASCADE,
                             verbose_name='City')
    language = models.ForeignKey('Language',
                                 on_delete=models.CASCADE,
                                 verbose_name='Programming language')
    url_data = jsonfield.JSONField(default=default_urls)

    class Meta:
        unique_together = ("city", "language")

    def __str__(self):
        return '{} {}'.format(self.city, self.language)
Пример #9
0
class SQLProduct(models.Model):
    """
    A SQL based clone of couch Products.

    This is used to efficiently filter StockState and other
    SQL based queries to exclude data for archived products.
    """
    domain = models.CharField(max_length=255, db_index=True)
    product_id = models.CharField(max_length=100, db_index=True, unique=True)
    name = models.CharField(max_length=100, null=True)
    is_archived = models.BooleanField(default=False)
    code = models.CharField(max_length=100, default='', null=True)
    description = models.TextField(null=True, default='')
    category = models.CharField(max_length=100, null=True, default='')
    program_id = models.CharField(max_length=100, null=True, default='')
    cost = models.DecimalField(max_digits=20, decimal_places=5, null=True)
    units = models.CharField(max_length=100, null=True, default='')
    product_data = jsonfield.JSONField(
        default=dict,
    )
    created_at = models.DateTimeField(auto_now_add=True)
    last_modified = models.DateTimeField(auto_now=True)

    objects = ProductManager()
    active_objects = OnlyActiveProductManager()

    def __str__(self):
        return "{} ({})".format(self.name, self.domain)

    def __repr__(self):
        return "<SQLProduct(domain=%s, name=%s)>" % (
            self.domain,
            self.name
        )

    @classmethod
    def by_domain(cls, domain):
        return cls.objects.filter(domain=domain).all()

    @property
    def get_id(self):
        return self.product_id

    @property
    def unit(self):
        # For compatibility with Product
        return self.units

    class Meta(object):
        app_label = 'products'
Пример #10
0
class TestCases(models.Model):
    sl_no = models.IntegerField(blank=True, null=True)
    problem = models.ForeignKey(Problem,
                                blank=True,
                                null=True,
                                on_delete=models.CASCADE)
    correct_ans = models.TextField(blank=True, null=True)
    testInput = models.TextField()
    testCase = models.TextField()
    ans_choice = jsonfield.JSONField(max_length=1000, blank=True, null=True)
    display = models.BooleanField(default=True)

    def __str__(self):
        return (self.problem.pblm_id).encode('ascii', errors='replace')
Пример #11
0
class Book(models.Model):
    unique_id = models.UUIDField(default=uuid.uuid4,
                                 editable=False,
                                 unique=True)
    authors = models.ManyToManyField(Author)
    editors = models.ManyToManyField(Editor, null=True, blank=True)
    interpreters = models.ManyToManyField(Interpreter, null=True, blank=True)
    book_types = models.ManyToManyField(BookType)
    number_pub = models.SmallIntegerField()
    add_info = jsonfield.JSONField(null=True, blank=True)
    pub_date = models.DateField('date published')
    city = models.CharField(max_length=200)
    publisher = models.CharField(max_length=200)
    pages = models.IntegerField()
Пример #12
0
class Place(models.Model):
    CATEGORY = (('province', 'Province'),
                ('city', 'City'),
                ('district', 'District'),)

    category = models.SlugField(choices=CATEGORY, default='city')
    parent = models.ForeignKey('self', blank=True, null=True)

    name = models.CharField(max_length=50, blank=True, null=True)

    data = jsonfield.JSONField(blank=True, null=True)

    def __unicode__(self):
        return u'%s (%s)' % (unicode(self.name), self.category)
Пример #13
0
class NativeField(BaseModel):
    '''
    原生字段
    '''
    SUBJECT_CHOICES = (
        ('user', '内部联系人'),    # '^[a-z]{1,16}$'
        ('extern_user', '外部联系人'),
    )
    name = models.CharField(max_length=128, verbose_name='字段名称')
    key = models.CharField(max_length=256, verbose_name='内部字段名')
    subject = models.CharField(choices=SUBJECT_CHOICES, default='user', max_length=128, verbose_name='字段分类')
    schema = jsonfield.JSONField(default={'type': 'string'}, verbose_name='字段定义')
    is_visible = models.BooleanField(default=True, verbose_name='是否展示')
    is_visible_editable = models.BooleanField(default=True, verbose_name='对于`是否展示`,是否可以修改')
Пример #14
0
class ProfileIPData(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    relation = models.ForeignKey('ProfileIP',
                                 on_delete=models.CASCADE,
                                 related_name='data_versions')
    data = jsonfield.JSONField(default={})
    version = models.IntegerField(default=0)
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['version']
        permissions = (('profile_management', 'Can manage profiles'), )
Пример #15
0
class CustomField(BaseModel):
    '''
    自定义字段
    '''

    SUBJECT_CHOICES = (
        ('user', '内部联系人'),    # '^[a-z]{1,16}$'
        ('extern_user', '外部联系人'),
    )

    name = models.CharField(max_length=128, verbose_name='字段名称')
    subject = models.CharField(choices=SUBJECT_CHOICES, default='user', max_length=128, verbose_name='字段分类')
    schema = jsonfield.JSONField(default={'type': 'string'}, verbose_name='字段定义')
    is_visible = models.BooleanField(default=True, verbose_name='是否展示')
Пример #16
0
class Url(models.Model):
    city = models.ForeignKey('City',
                             on_delete=models.CASCADE,
                             verbose_name='Город')
    language = models.ForeignKey('Language',
                                 on_delete=models.CASCADE,
                                 verbose_name='Язык программирования')
    url_data = jsonfield.JSONField(default=default_urls)

    class Meta:
        unique_together = ('city', 'language')

    def __str__(self):
        return f'{self.language}, {self.city}'
Пример #17
0
class MangoPayPayIn(models.Model):
    mangopay_id = models.PositiveIntegerField(null=True, blank=True)
    mangopay_user = models.ForeignKey(MangoPayUser,
                                      related_name="mangopay_payins")
    mangopay_wallet = models.ForeignKey(MangoPayWallet,
                                        related_name="mangopay_payins")

    execution_date = models.DateTimeField(blank=True, null=True)
    status = models.CharField(max_length=9,
                              choices=STATUS_CHOICES,
                              blank=True,
                              null=True)
    debited_funds = MoneyField(default=0,
                               default_currency="EUR",
                               decimal_places=2,
                               max_digits=12)
    fees = MoneyField(default=0,
                      default_currency="EUR",
                      decimal_places=2,
                      max_digits=12)
    result_code = models.CharField(null=True, blank=True, max_length=6)
    payment_type = models.CharField(null=False,
                                    blank=False,
                                    choices=PAYIN_PAYMENT_TYPE,
                                    max_length=10)

    # Pay in by card via web - mangopay_card needs custom validation so it's not null on save
    mangopay_card = models.ForeignKey("MangoPayCard",
                                      related_name="mangopay_payins",
                                      null=True,
                                      blank=True)
    secure_mode_redirect_url = models.URLField(null=True, blank=True)

    # Pay in via bank wire
    wire_reference = models.CharField(null=True, blank=True, max_length=50)
    mangopay_bank_account = jsonfield.JSONField(null=True, blank=True)

    def create(self):
        pay_in = self.get_pay_in()
        self.mangopay_id = pay_in.get_pk()
        self._update(pay_in)

    def get_pay_in(self):
        raise NotImplemented

    def _update(self, pay_in):
        self.execution_date = get_execution_date_as_datetime(pay_in)
        self.status = pay_in.status
        self.save()
        return self
Пример #18
0
class Url(models.Model):
    city = models.ForeignKey('City', on_delete=models.CASCADE,
                             verbose_name='Город')
    language = models.ForeignKey('Language', on_delete=models.CASCADE,
                                 verbose_name='Язык программирования')
    url_data = jsonfield.JSONField(default=default_urls)#т.е. мы подготовили словарь

    def __str__(self):
        # return "{}, {}".format(self.title, self.user)
        return "Город: {} и ЯП: {}".format(self.city, self.language)
    class Meta:
        verbose_name = 'URL адреса'
        verbose_name_plural = 'URL адреса'
        unique_together = ("city", "language") # т.е для города киев и специальности пайтон не может быть больше чем одна строка
Пример #19
0
class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    array = jsonfield.JSONField()
    arrayratedmoviesindxs = jsonfield.JSONField()
    name = models.CharField(max_length=1000)
    lastrecs = jsonfield.JSONField()

    def __unicode__(self):
        return self.name

    def save(self, *args, **kwargs):
        create = kwargs.pop('create', None)
        recsvec = kwargs.pop('recsvec', None)
        print 'create:', create
        if create == True:
            super(UserProfile, self).save(*args, **kwargs)
        elif recsvec is not None:
            self.lastrecs = json.dumps(recsvec.tolist())
            super(UserProfile, self).save(*args, **kwargs)
        else:
            nmovies = MovieData.objects.count()
            array = np.zeros(nmovies)
            # print 'SH1 Array', len(array)
            ratedmovies = self.ratedmovies.all()
            self.arrayratedmoviesindxs = json.dumps(
                [m.movieindx for m in ratedmovies])
            for m in ratedmovies:
                array[m.movieindx] = m.value
            print 'SH1 Array', len(array)
            print 'SH2 Array', array
            #self.array = json.dumps(array.tolist())
            self.array = array.tolist()
            # array_length = len(self.array)
            # self.array = array
            print 'SH3 Self array', len(self.array)
            print 'SH4 Self array', self.array
            super(UserProfile, self).save(*args, **kwargs)
Пример #20
0
class QueueTaskBase(BaseModel):
    task_name = models.CharField(verbose_name=_('Task Name'),
                                 max_length=255,
                                 default='Queued Task')
    task_class = models.CharField(verbose_name=_('Task Class'), max_length=100)
    task_args = jsonfield.JSONField(load_kwargs={'cls': DateJSONDecoder},
                                    verbose_name=_('Task args'),
                                    default=list,
                                    blank=True)
    task_kwargs = jsonfield.JSONField(load_kwargs={'cls': DateJSONDecoder},
                                      verbose_name=_('Task kwargs'),
                                      default=dict,
                                      blank=True)

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if self._state.adding:
            self.task_name = self._task_to_str()
        super().save(*args, **kwargs)

    def get_celery_task(self):
        return get_celery_task(self.task_class)

    def _task_to_str(self):
        task_str = None
        task_func = get_celery_task(self.task_class)
        if task_func and task_func.task_str:
            kwargs = self.task_kwargs
            try:
                task_str = task_func.task_to_str(self, *self.task_args,
                                                 **kwargs)
            except (AttributeError, ValueError, IndexError):
                # TODO: Improve exception
                task_str = task_func.task_name
        return task_str
Пример #21
0
class ShopifyFulFillment(ShopifyResource):
    """https://help.shopify.com/api/reference/fulfillment
    """
    id = models.BigIntegerField(primary_key=True)
    order = models.ForeignKey('ShopifyOrder', related_name='fulfillments')

    created_at = models.DateTimeField()
    created_timestamp = models.PositiveIntegerField(default=0)
    updated_at = models.DateTimeField(blank=True, null=True)
    updated_timestamp = models.PositiveIntegerField(default=0,
                                                    blank=True,
                                                    null=True)

    line_items = jsonfield.JSONField()
    notify_customer = models.BooleanField(default=True)
    receipt = jsonfield.JSONField()
    status = models.CharField(max_length=15, blank=True, null=True)
    tracking_company = models.CharField(max_length=63, blank=True, null=True)
    tracking_numbers = jsonfield.JSONField()
    tracking_urls = jsonfield.JSONField()
    variant_inventory_management = models.CharField(max_length=63,
                                                    blank=True,
                                                    null=True)

    class Meta:
        app_label = 'shopify'
        verbose_name = 'Shopify Fulfillment'

    def deserialize_value(self, key, value):
        if key in [
                'created_at',
                'updated_at',
        ]:
            value = parse_datetime(value) if value else None
        else:
            value = value
        return value
Пример #22
0
class CreateScheduleInstanceActionDefinition(CaseRuleActionDefinition):
    alert_schedule = models.ForeignKey('scheduling.AlertSchedule',
                                       null=True,
                                       on_delete=models.PROTECT)
    timed_schedule = models.ForeignKey('scheduling.TimedSchedule',
                                       null=True,
                                       on_delete=models.PROTECT)

    # A List of [recipient_type, recipient_id]
    recipients = jsonfield.JSONField(default=list)

    # (Optional, ignored if None) The name of a case property whose value will be tracked
    # over time on the schedule instance as last_reset_case_property_value.
    # Every time the case property's value changes, the schedule's start date is
    # reset to the current date.
    reset_case_property_name = models.CharField(max_length=126, null=True)

    @property
    def schedule(self):
        if self.alert_schedule_id:
            return self.alert_schedule
        elif self.timed_schedule_id:
            return self.timed_schedule

        raise ValueError("Expected a schedule")

    @schedule.setter
    def schedule(self, value):
        from corehq.messaging.scheduling.models import AlertSchedule, TimedSchedule

        self.alert_schedule = None
        self.timed_schedule = None

        if isinstance(value, AlertSchedule):
            self.alert_schedule = value
        elif isinstance(value, TimedSchedule):
            self.timed_schedule = value
        else:
            raise TypeError(
                "Expected an instance of AlertSchedule or TimedSchedule")

    def when_case_matches(self, case, rule):
        schedule = self.schedule
        if isinstance(schedule, AlertSchedule):
            refresh_case_alert_schedule_instances(case, schedule, self, rule)
        elif isinstance(schedule, TimedSchedule):
            refresh_case_timed_schedule_instances(case, schedule, self, rule)

        return CaseRuleActionResult()
Пример #23
0
class ParamedModel(six.with_metaclass(ParamedModelType, models.Model)):
    """Parameterizable class

    This class allows all derived classes to be polymorphically extended
    by extra fields by using :class:`ParamField` and :class:`ParamMultiField`.
    First derived class of :class:`ParamModel` must be non-abstract to
    create a real database table and all subsequent derived classes are
    atomaticlly marked as abstract by :class:`ParamedModelType`. This is
    made to avoid creation of db tables for derived classes. See mode
    info about how it is implemented in metaclass :class:`ParamedModelType`.

    The class has two fields:
    * params - this is a jsonfield where all extra fields are stored and
               serialized to json string when the instance is saved to db
    * _class - a :class:`ParamField` which stores path to the derived
               class. It allows to load the same derived class after
               loading data from db.
    """
    class Meta(object):
        abstract = True

    objects = ParamedModelManager()

    params = jsonfield.JSONField(default={})
    _class = ParamField()

    @classmethod
    def get_defined_params(cls):
        param_names = []
        for basecls in cls.__mro__:
            if not hasattr(basecls, '_param_field_names'):
                continue
            # noinspection PyProtectedMember
            param_names += basecls._param_field_names
        return param_names

    def set_default_params(self):
        for basecls in self.__class__.__mro__:
            if not hasattr(basecls, '_param_field_names'):
                continue
            # noinspection PyProtectedMember
            for param in basecls._param_field_names:
                basecls.__dict__[param].set_default_value(self)

    def save(self, *args, **kwargs):
        # store current class to _class attribute
        self._class = loader.get_class_path(self)
        self.set_default_params()
        return super(ParamedModel, self).save(*args, **kwargs)
Пример #24
0
class Story(models.Model):
    title = models.CharField(max_length=64,
                             verbose_name='Название истории',
                             unique=True)
    description = models.CharField(max_length=256,
                                   verbose_name='Описание истории',
                                   unique=True)
    data = jsonfield.JSONField(default=default_story)

    class Meta:
        verbose_name = 'История'
        verbose_name_plural = 'Истории'

    def __str__(self):
        return self.title
Пример #25
0
class Answer(models.Model):
    user = models.ForeignKey(User,
                             on_delete=models.SET_NULL,
                             blank=True,
                             null=True,
                             verbose_name='Юзер')
    quiz_id = models.ForeignKey(Quiz,
                                blank=True,
                                null=True,
                                on_delete=models.SET_NULL,
                                verbose_name='Опрос')
    answer = jsonfield.JSONField('Ответы',
                                 null=True,
                                 blank=True,
                                 max_length=255)
Пример #26
0
class Word(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

    base_word = models.TextField()
    base_language = models.ForeignKey(Language,
                                      on_delete=models.CASCADE,
                                      related_name="base_language")

    translated_word = jsonfield.JSONField()
    foreign_language = models.ForeignKey(Language,
                                         on_delete=models.CASCADE,
                                         related_name="foreign_language")

    def __str__(self):
        return f'{self.base_word}'
Пример #27
0
class ServiceType(models.Model):
    Vendor = Choices((1, "aliyun", _("aliyun")), (2, "tencent", _("tencent")))
    Service = Choices((1, "sms", _("sms")))
    title = models.CharField(max_length=255)
    vendor = models.IntegerField(default=Vendor.aliyun, choices=Vendor)
    service = models.IntegerField(default=Service.sms, choices=Service)
    options = jsonfield.JSONField()

    class Meta:
        verbose_name = _("service-type")
        verbose_name_plural = _("service-type")

    def __str__(self):
        return "{} - {}".format(self.get_vendor_display(),
                                self.get_service_display())
Пример #28
0
class questionTranslation(models.Model):
    questionTranslationID = models.AutoField(db_column='questionTranslationID',
                                             primary_key=True)
    questionID = models.ForeignKey(question,
                                   db_column='questionID',
                                   to_field='questionID',
                                   on_delete=models.CASCADE)
    languageCodeID = models.ForeignKey(code,
                                       db_column='languageCodeID',
                                       to_field='codeID',
                                       on_delete=models.CASCADE)
    translation = jsonfield.JSONField()
    modified_on = models.DateTimeField(auto_now_add=True)
    modified_by = models.CharField(max_length=50, default='default value')
    Identifier = models.CharField(max_length=50)
Пример #29
0
class NonUserProfile(BaseProfile):
    '''
        For people who want to sign up but not create an account.
    '''
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('e-mail address'))
    date_created = models.DateTimeField(auto_now_add=True)
    extra_fields = jsonfield.JSONField(blank=True, null=True)

    class Meta:
        ordering = ['-date_created']

    def __unicode__(self):
        return u'{0}, {1}: {2}'.format(self.first_name, self.last_name, self.email)
Пример #30
0
class MaintenanceRule(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True)

    # cron syntax, blank for manual only appraisal
    frequency = models.CharField(max_length=255, blank=True, default='')

    # empty for all files in IP or all fields in tree node
    specification = jsonfield.JSONField(null=True, default=None)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    public = models.BooleanField(default=True)

    class Meta:
        abstract = True