Beispiel #1
0
 def update_statistics(cls, char):
     result = Character.objects.filter(char=char).aggregate(
         correct_cnt=Sum(
             Case(When(is_correct=1, then=Value(1)),
                  default=Value(0),
                  output_field=SmallIntegerField())),
         err_cnt=Sum(
             Case(When(is_correct=-1, then=Value(1)),
                  default=Value(0),
                  output_field=SmallIntegerField())),
         uncheck_cnt=Sum(
             Case(When(is_correct=0, then=Value(1)),
                  default=Value(0),
                  output_field=SmallIntegerField())),
         total_cnt=Count('is_correct'),
         recog_diff_count=Sum(
             Case(When(is_correct=-1, is_same=1, then=Value(1)),
                  When(is_correct=1, is_same=-1, then=Value(1)),
                  default=Value(0),
                  output_field=SmallIntegerField())))
     # add character statistics, if it's missing.
     statistics, created = CharacterStatistics.objects.get_or_create(
         char=char)
     CharacterStatistics.objects.filter(char=char).update(
         uncheck_cnt=result['uncheck_cnt'],
         correct_cnt=result['correct_cnt'],
         err_cnt=result['err_cnt'],
         total_cnt=result['total_cnt'],
         recog_diff_count=result['recog_diff_count'])
Beispiel #2
0
    def get_queryset(self):
        pier_qs = Pier.objects.filter(
            harbor=OuterRef("pk")).values("harbor__pk")
        width_qs = pier_qs.annotate(max=Max("max_width")).values("max")
        length_qs = pier_qs.annotate(max=Max("max_length")).values("max")
        depth_qs = pier_qs.annotate(max=Max("max_depth")).values("max")
        number_of_free_places_qs = pier_qs.annotate(
            count=Sum("number_of_free_places")).values("count")
        number_of_inactive_places_qs = pier_qs.annotate(
            count=Sum("number_of_inactive_places")).values("count")
        number_of_places_qs = pier_qs.annotate(
            count=Sum("number_of_places")).values("count")

        return (super().get_queryset().annotate(
            max_width=Subquery(width_qs, output_field=DecimalField()),
            max_length=Subquery(length_qs, output_field=DecimalField()),
            max_depth=Subquery(depth_qs, output_field=DecimalField()),
            number_of_free_places=Subquery(number_of_free_places_qs,
                                           output_field=SmallIntegerField()),
            number_of_inactive_places=Subquery(
                number_of_inactive_places_qs,
                output_field=SmallIntegerField()),
            number_of_places=Subquery(number_of_places_qs,
                                      output_field=SmallIntegerField()),
            electricity=BoolOr("piers__electricity"),
            water=BoolOr("piers__water"),
            gate=BoolOr("piers__gate"),
            mooring=BoolOr("piers__mooring"),
            waste_collection=BoolOr("piers__waste_collection"),
            lighting=BoolOr("piers__lighting"),
        ))
Beispiel #3
0
class Image(Model):
    source = URLField(max_length=255)
    url = URLField(max_length=255, null=True)
    file_size = SmallIntegerField(null=True)
    point = SmallIntegerField(default=5)
    posted_date = DateTimeField(null=True)
    created_at = DateTimeField(auto_now_add=True)
    updated_at = DateTimeField(auto_now=True)
class ChitBatch(Model):
    name = CharField(max_length=25, unique=True, blank=False)
    members = ManyToManyField(Member)
    no_of_members = SmallIntegerField(blank=False, default=0)
    principal = IntegerField(blank=False)
    commission_percent = IntegerField(default=5, blank=False)
    balance = IntegerField(blank=False, default=0)
    shortage = IntegerField(blank=False, default=0)
    period = SmallIntegerField(blank=False)
    dues = SmallIntegerField(blank=False)
    start_date = DateField(blank=False)
    start_time = TimeField(blank=False)
    is_active = BooleanField(default=True)
    end_date = TimeField(blank=True, null=True)
    created_on = DateTimeField(auto_now_add=True)

    @property
    def commission(self):
        return (self.principal * self.commission_percent) / 100

    @property
    def auction_amt(self):
        return (self.principal - self.get_commission()) + self.balance

    @property
    def last_auction_date(self):
        if self.next_auction != self.start_date:
            return self.next_auction - relativedelta(months=+1)

    def max_shortage(self, bid_amount):
        possible_balance = self.balance + bid_amount - self.get_commission()
        return (self.principal - bid_amount) - (possible_balance)

    def update_balance(self, bid_amt):
        self.balance = self.balance + bid_amt - self.get_commission()

    def update_payment_record(self):
        if self.next_auction:
            if not self.is_multiple_auction:
                paid = PaymentRecordEnum.UN_PAID
            else:
                paid = PaymentRecordEnum.CHIT_BENIFIT
            prs = []
            for member in self.members.all():
                prs.append(
                    PaymentRecord(
                        chitbatch=self,
                        member=member,
                        bid_date=self.next_auction,
                        paid=paid,
                    ))
            PaymentRecord.objects.bulk_create(prs)

    def is_another_auction_possible(self, bid_amount):
        latest_balance = self.balance + (bid_amount - self.get_commission())
        if (latest_balance - bid_amount) > (0.06 * self.principal):
            return True
        return False
Beispiel #5
0
class Event(Model):
    start = SmallIntegerField(default=0)
    down = SmallIntegerField(default=0)
    date = DateField(auto_now=True)
    hour = TimeField(auto_now=True)
    lat = CharField(max_length=25)
    long = CharField(max_length=25)
    direction = CharField(max_length=50)

    def __str__(self):
        return f'{self.start}-{self.down}'
Beispiel #6
0
class DataHistoryModel(Model):
    class Meta:
        abstract = True

    industry = CharField(max_length=60, help_text="所属行业")
    deploy_way = SmallIntegerField(choices=DEPLOY_WAYS, help_text="部署方式")
    cli_version = SmallIntegerField(choices=CLI_CHOICES, help_text="客户版本")

    created_at = DateTimeField(auto_now=True, help_text="创建时间")
    updated_at = DateTimeField(auto_now_add=True, help_text="更新时间")
    date = DateField(help_text="记录时间")
Beispiel #7
0
class EmotionWord(Model):
    word = CharField(null=False, max_length=128)

    emotion = SmallIntegerField(
        null=False, choices=[(e.name, e.value) for e in EmotionType]
    )
    part = SmallIntegerField(
        null=False, choices=[(e.name, e.value) for e in PartType]
    )

    def __str__(self):
        return f'{self.id} : {self.word}'
Beispiel #8
0
def small_integer( *args, **kwargs ):
	
	meta = _kwargs_( kwargs )

	meta['type'] = 'integer'

	meta['small'] = True

	field = SmallIntegerField( *args, **kwargs )

	field.meta = meta

	return field
Beispiel #9
0
class Question(Model):
    ref = ForeignKey('self',
                     db_column='ref_id',
                     blank=True,
                     null=True,
                     related_name='distortion',
                     verbose_name='原题')
    charpter = ForeignKey(Charpter,
                          db_column='charpter_id',
                          related_name='questions',
                          verbose_name='归属章节')
    content = TextField(verbose_name='题目内容')
    type = ForeignKey(CodeQuesthionType,
                      db_column='type',
                      related_name='questions',
                      verbose_name='题目类型')
    owner = ForeignKey(Org,
                       db_column='owner',
                       related_name='own_questions',
                       verbose_name='所有人')
    answer = TextField(blank=True, default='', verbose_name='回答')
    answer_type = ForeignKey(CodeContextType,
                             db_column='answer_type',
                             verbose_name='答题类型')
    difficultly = SmallIntegerField(default=1, verbose_name='难度')
    solve = TextField(blank=True, default='', verbose_name='解析')
    created_date = DateTimeField(auto_now_add=True)
    created_by = ForeignKey(User,
                            db_column='created_by',
                            related_name='created_questions',
                            verbose_name='创建者')
    edit_by = ForeignKey(User,
                         db_column='edit_by',
                         related_name='edited_questions',
                         null=True,
                         blank=True,
                         verbose_name='编辑者')
    status = SmallIntegerField(default=1, verbose_name='状态')
    share = NullBooleanField(null=True, default=False, verbose_name='是否可以分享')
    library = ForeignKey(Library, db_column='library_id', verbose_name='图书馆')
    comments = CharField(max_length=500, blank=True, verbose_name='备注')

    class Meta:
        app_label = 'question'
        db_table = 'questions'
        verbose_name = '题目'
        verbose_name_plural = '题目'

    def __unicode__(self):
        return u'{0}...'.format(self.content[:10])
Beispiel #10
0
class UserProfile(AbstractBaseUser, PermissionsMixin):
    GENDER_MALE = 0
    GENDER_FEMALE = 1
    GENDER_DIVERSE = 2
    GENDER_OPTIONS = (
        (GENDER_MALE, "male"),
        (GENDER_FEMALE, "female"),
        (GENDER_DIVERSE, "diverse"),
    )

    FOOD_OMNIVOUROUS = 0
    FOOD_VEGETARIAN = 1
    FOOD_OPTIONS = ((FOOD_OMNIVOUROUS, "omnivourous"), (FOOD_VEGETARIAN, "vegetarian"))

    email = EmailField(unique=True, verbose_name="Email address")
    is_active = BooleanField(default=True)
    is_staff = BooleanField(default=False)
    gender = SmallIntegerField(choices=GENDER_OPTIONS)
    food_preference = SmallIntegerField(choices=FOOD_OPTIONS)
    first_name = CharField(max_length=254, verbose_name="First name")
    last_name = CharField(max_length=254, verbose_name="Last name")
    birth_date = DateField()
    phone = IntegerField()
    address_line_1 = CharField(max_length=254)
    address_line_2 = CharField(max_length=254, blank=True, null=True)
    zip = CharField(max_length=254)
    city = CharField(max_length=254)
    state = CharField(max_length=254)

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = [
        "gender",
        "food_preference",
        "first_name",
        "last_name",
        "birth_date",
        "phone",
        "address_line_1",
        "zip",
        "city",
        "state",
    ]

    objects = UserManager()

    def get_full_name(self):
        return self.first_name + " " + self.last_name

    def get_short_name(self):
        return self.first_name
Beispiel #11
0
class ModelEvent(BaseModel):
    """
    Used to record model entry events, like modification, removal or adding of
    values or relationships.
    """

    operation = SmallIntegerField(
        validators=[MinValueValidator(-1),
                    MaxValueValidator(1)],
        null=True,
        choices=DjangoOperations,
    )

    user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE,
                      null=True)  # maybe don't cascade?
    entry = ForeignKey(ModelEntry, on_delete=CASCADE)

    # modifications = None  # One2Many -> ModelModification
    # relationships = None  # One2Many -> ModelRelationship

    # v experimental, opt-in (pickled object)
    snapshot = PickledObjectField(null=True)
    performance = DurationField(null=True)

    class Meta:
        verbose_name = "Model Event"
        verbose_name_plural = "Model Events"

    class LoggingIgnore:
        complete = True
Beispiel #12
0
class Role(Model):
	name = CharField(max_length=100, db_index=True, help_text=_(u'Required \
		field, max 100 characters. E.g. Profesori, Studenti'),
		verbose_name=_(u'Name'))
	singular_name = CharField(max_length=100, blank=True, verbose_name=_(u'\
		Singular name'), help_text=_(u'Optional field, max 100 characters. \
		E.g. Profesor, Student'))
	shortname = CharField(max_length=50, blank=True, verbose_name=_(u'Short \
		name'), help_text=_(u'Optional field, e.g. prof fro Professor. Used \
		in the listing page.'))
	description = TextField(blank=True, help_text=_(u'Optional field'),
		verbose_name=_(u'Description'))
	o = SmallIntegerField(blank=True, null=True, verbose_name=_(u'Order'),
		help_text=_(u'Optional field, only numeric values allowed. Defines the \
		order of the role in various pages.'))
	active = BooleanField(default=True, db_index=True, help_text=_(u'Uncheck \
		to deactivate this role. This should occur only in the event of \
		academic title changes.'), verbose_name=_(u'Active'))

	class Meta:
		verbose_name = _(u'Role')
		verbose_name_plural = _(u'Roles')
		ordering = ('o', 'id',)

	def __unicode__(self):
		return u'%s' % self.name
Beispiel #13
0
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'
Beispiel #14
0
class Registration(Model):

    invoce = ForeignKey('Invoice', verbose_name='накладная',
                        null=True, blank=True, default=None,
                        on_delete=PROTECT)
    metka = ForeignKey('Invoice', verbose_name='метка', related_name='metka',
                        null=True, blank=True, default=None,
                        on_delete=PROTECT)
    from_of = ForeignKey('Contractor', verbose_name='Котрагент',
                         null=False, blank=True, default=None,
                         on_delete=PROTECT)
    product = ForeignKey('Product', verbose_name='товар',
                         null=False, blank=True, default=None,
                         on_delete=PROTECT)
    dish = ForeignKey('Dish', verbose_name='блюдо',
                         null=True, blank=True, default=None,
                         on_delete=PROTECT)    
    motion = SmallIntegerField(choices=TYPE_CHOICES, default=ARRIVAL)
    qty = DecimalField(max_digits=15, decimal_places=3,
                       default=0,verbose_name='количество')
    summa = DecimalField(max_digits=15, decimal_places=2,
                         default=0,verbose_name='сумма')
    created_at = DateField(verbose_name ='создано',null=False,
                               db_index=True)
    class Meta:
        app_label = 'calculation'
        verbose_name = 'Запись регистра "Cклад"'
        verbose_name_plural = 'Регистр "Cклад"'
        ordering = ['product','created_at']
Beispiel #15
0
class Area(MPTTModel):
    # 地区表
    parent = TreeForeignKey('self',
                            db_column='parent_id',
                            null=True,
                            blank=True,
                            related_name='children',
                            verbose_name='上级')
    # path = CharField(max_length=200, blank=True, verbose_name='具体位置')
    # level = SmallIntegerField(blank=True, default=4, verbose_name='级别')
    name = CharField(max_length=50, blank=True, verbose_name='名称')
    short_name = CharField(max_length=50, blank=True, verbose_name='简称')
    longitude = FloatField(blank=True,
                           default=1.1,
                           null=True,
                           verbose_name='经度')
    latitude = FloatField(blank=True,
                          default=2.2,
                          null=True,
                          verbose_name='纬度')
    sort = IntegerField(blank=True, default=1)
    status = SmallIntegerField(blank=True, default=2, verbose_name='状态')

    class Meta:
        app_label = 'education'
        db_table = 'area'
        verbose_name = '地区'
        verbose_name_plural = '地区'

    def __unicode__(self):
        return u'{0}'.format(self.name)
Beispiel #16
0
class Location(Model):
    #change theverbose name 'description' to 'name'. by lxy
    name = CharField(_('location name'), max_length=100)
    type = SmallIntegerField(choices=LOCATION_TYPE_CHOICES,
                             default=1,
                             verbose_name=_("location type"))
    code = CharField(_('location code'), max_length=25, unique=True)
    description = CharField(_('location description'),
                            max_length=100,
                            blank=True,
                            null=True)
    lon = FloatField(_('longitude'), blank=True, null=True)
    lat = FloatField(_('latitude'), blank=True, null=True)
    created_at = DateTimeField(_('created at'), auto_now_add=True)
    updated_at = DateTimeField(_('updated at'), auto_now=True)
    updated_by = ForeignKey(User, verbose_name=_("updated_by"))
    objects = LocationManager()

    class Meta:
        verbose_name = _('location')
        verbose_name_plural = _('locations')
        ordering = ('type', '-updated_at')

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

    def natural_key(self):
        return (self.code, )
Beispiel #17
0
class ModelHistory(DjangoModel):
    class Meta:
        unique_together = (("id", "history_id"), )

    # History fields
    history_id = BigAutoField(primary_key=True)
    history_transaction = BigIntegerField(null=False)

    # AbstractModel fields
    id = BigIntegerField(null=False)
    status = SmallIntegerField(null=False)
    version = IntegerField(null=False)
    last_transaction = BigIntegerField(null=False)

    # Model fields
    type = IntegerField(null=False)
    optimistic_lock_count = IntegerField(null=False)
    data = JSONField(null=False)

    # Model fields : not required
    # 디버깅 목적으로 켜서 저장을 해야 할 수도 있기 때문에 null=True 로 컬럼을 만들어 둔다
    computed = JSONField(null=True)
    raw = JSONField(null=True)
    computed_uri_hash = UUIDField(null=True)
    computed_owner_id = BigIntegerField(null=True)
    computed_container_id = BigIntegerField(null=True)
    computed_proprietor_id = BigIntegerField(null=True)
    computed_search_array = ArrayField(BigIntegerField(), null=True)
Beispiel #18
0
class CharacterGroup(Model):
    """A mnodel for storing default knowledge packet sets for groups of
     characters. These should be automatically added to the knowlege packets of
     a newly created Character that belongs to a CharacterGroup (by signals).
    """
    name = CharField(max_length=250)
    author = FK(
        to=Profile,
        related_name='character_groups_authored',
        on_delete=SET_NULL,
        blank=True,
        null=True,
    )
    characters = M2M(to=Character, related_name='character_groups')
    default_knowledge_packets = M2M(
        to=KnowledgePacket,
        related_name='character_group_defaults',
        blank=True,
    )
    default_skills = M2M(to=Skill,
                         related_name='character_group_defaults',
                         blank=True)
    order_no = SmallIntegerField(default=1)

    class Meta:
        ordering = ['order_no', 'name']
        unique_together = ('name', 'author')
        verbose_name = '* CHARACTER GROUP'
        verbose_name_plural = '* CHARACTER GROUPS'

    def __str__(self):
        return f"{self.name} [{self.author}]"
Beispiel #19
0
class TypeDeCaracteristiqueDeProgramme(CommonModel):
    nom = CharField(_('nom'),
                    max_length=200,
                    help_text=ex(_('tonalité')),
                    unique=True,
                    db_index=True)
    nom_pluriel = CharField(_('nom (au pluriel)'),
                            max_length=230,
                            blank=True,
                            help_text=PLURAL_MSG)
    classement = SmallIntegerField(_('classement'), default=1)

    class Meta(object):
        verbose_name = _('type de caractéristique de programme')
        verbose_name_plural = _('types de caractéristique de programme')
        ordering = ('classement', )

    @staticmethod
    def invalidated_relations_when_saved(all_relations=False):
        return ('caracteristiques', )

    def pluriel(self):
        return calc_pluriel(self)

    def __str__(self):
        return self.nom

    @staticmethod
    def autocomplete_search_fields():
        return 'nom__unaccent__icontains', 'nom_pluriel__unaccent__icontains',
Beispiel #20
0
class Member(Model):
    from choices_member import UNDER_20, BTWN_20_29, BTWN_30_39, BTWN_40_44, BTWN_45_49, BTWN_50_59, OVER_60
    from choices_member import FEMALE, MALE
    from choices_member import WHITE, BLACK, HISPANIC, ASIAN, OTHER
    from choices_member import YES, NO
    from choices_member import BMI_UNDER, BMI_OVER
    from choices_member import AGE_RANGE_CHOICES, SEX_CHOICES, ETHNICITY_CHOICES, DRINK_CHOICES, SMOKE_CHOICES, EXERCISE_CHOICES, BMI_CHOICES, RELATIVE_CHOICES

    circle = ForeignKey(Circle)
    circle_owner = BooleanField(default=False)
    member_name = CharField(max_length=100)
    member_created_date = DateTimeField('member created on',
                                        null=True,
                                        blank=True)
    member_email = CharField(max_length=200, null=True, blank=True)
    member_phone = CharField(max_length=25, null=True, blank=True)

    age_range = CharField(max_length=5,
                          choices=AGE_RANGE_CHOICES,
                          default=BTWN_20_29)

    sex_range = CharField(max_length=2, choices=SEX_CHOICES, default=FEMALE)

    ethnicity_range = CharField(max_length=3,
                                choices=ETHNICITY_CHOICES,
                                default=WHITE)

    bmi_range = CharField(max_length=3, choices=BMI_CHOICES, default=BMI_UNDER)

    smoker = BooleanField(default=False)
    drinker = BooleanField(default=False)
    exercises = BooleanField(default=True)

    cancer_family = SmallIntegerField(default=0)

    member_profile_entered_date = DateTimeField('profile entered on',
                                                null=True,
                                                blank=True)

    def risk(self):
        female_risk_percentage = {
            UNDER_20: 0.0000,
            BTWN_20_29: 0.0006,
            BTWN_30_39: 0.0044,
            BTWN_40_44: 0.0145,
            BTWN_45_49: 0.0145,
            BTWN_50_59: 0.0233,
            OVER_60: 0.0345,
        }

        male_risk_percentage = 0.0010

        return

    def add_reminders(self):
        return

    def __unicode__(self):
        return self.member_name
Beispiel #21
0
class ModelRelationshipModification(BaseModel):
    """
    Used to record the model entry even modifications of relationships. (M2M, Foreign)


    The operation attribute can have 4 valid values:
    -1 (delete), 0 (modify), 1 (create), None (n/a)

    field is the field where the relationship changed (entry got added or removed)
    and model is the entry that got removed/added from the relationship.
    """

    operation = SmallIntegerField(
        validators=[MinValueValidator(-1),
                    MaxValueValidator(1)],
        null=True,
        choices=DjangoOperations,
    )

    field = ForeignKey(ModelField, on_delete=CASCADE)
    entry = ForeignKey(ModelEntry, on_delete=CASCADE)

    event = ForeignKey(ModelEvent,
                       on_delete=CASCADE,
                       related_name='relationships')

    class Meta:
        verbose_name = "Model Entry Event Relationship Modification"
        verbose_name_plural = "Model Entry Event Relationship Modifications"

    class LoggingIgnore:
        complete = True

    def __str__(self) -> str:
        operation = Operation(self.operation)
        past = {v: k for k, v in PastM2MOperationMap.items()}[operation]

        return (f'[{self.field.mirror.application}:'
                f'{self.field.mirror.name}:'
                f'{self.field.name}] '
                f'{past} {self.entry}')

    def short(self) -> str:
        """
        short representation
        """
        operation = Operation(self.operation)
        shorthand = {v: k for k, v in ShortOperationMap.items()}[operation]
        return f'{shorthand}{self.entry.short()}'

    def medium(self) -> [str, str]:
        """
        short representation analogue of __str__ with additional field context
        :return:
        """
        operation = Operation(self.operation)
        shorthand = {v: k for k, v in ShortOperationMap.items()}[operation]

        return f'{shorthand}{self.field.name}', f'{self.entry.short()}'
Beispiel #22
0
 def load_rating(self):
     """
     Add object rating to queryset
     """
     return self.annotate(rating=Sum(
         Case(When(votes__value=False, then=-1),
              When(votes__value=True, then=1),
              default=0,
              output_field=SmallIntegerField())))
Beispiel #23
0
class LessonPage(Page):
    page_type = CharField(max_length=100, choices=PAGE_CHOICES, default='none')
    show_in_sitemap = BooleanField(default=True)
    menu_title = TextField(blank=True)
    is_nav_root = BooleanField(default=False)
    is_selectable = BooleanField(default=True)
    reference_title = TextField(null=True, blank=True)
    subtitle = TextField(null=True, blank=True)
    lesson_number = SmallIntegerField(blank=True, null=True)
    summary = CharField(max_length=100, null=True, blank=True)
    repetition_material = CharField(max_length=100, null=True, blank=True)
    audio_material = CharField(max_length=100, null=True, blank=True)
    comments_for_lesson = StreamField(
        [('advertisement', AdvertisementInline()),
         ('paragraph', RichTextBlock()), ('image', ImageChooserBlock()),
         ('document', DocumentViewerBlock()), ('html', RawHTMLBlock()),
         ('audio', AudioBlock()), ('video', VideoPlayerBlock()),
         ('post', PostBlock())],
        null=True,
        blank=True)
    body = StreamField([
        ('advertisement', AdvertisementInline()),
        ('paragraph', RichTextBlock()),
        ('image', ImageChooserBlock()),
        ('document', DocumentViewerBlock()),
        ('html', RawHTMLBlock()),
        ('audio', AudioBlock()),
        ('video', VideoPlayerBlock()),
        ('post', PostBlock()),
    ],
                       blank=True)
    dictionary = StreamField(
        [('advertisement', AdvertisementInline()),
         ('paragraph', RichTextBlock()), ('image', ImageChooserBlock()),
         ('document', DocumentViewerBlock()), ('html', RawHTMLBlock()),
         ('audio', AudioBlock()), ('video', VideoPlayerBlock()),
         ('translations',
          ListBlock(StructBlock([('word', RichTextBlock(required=True)),
                                 ('translation', RichTextBlock(required=True))
                                 ]),
                    template="blocks/transcriptions.html")),
         ('post', PostBlock())],
        null=True,
        blank=True)
    other_tabs = StreamField([('tab', TabBlock())], blank=True)

    def get_lesson_number(self):
        return self.slug.split("lecon-", 1)[1]

    has_own_topic = BooleanField(default=False)
    topic = OneToOneField(Topic, on_delete=SET_NULL, null=True, blank=True)

    def get_nav_root(self) -> Page:
        return get_nav_root(self)

    class Meta:
        permissions = (('listen_lesson', 'Can listen lesson'), )
Beispiel #24
0
class Lunbo(models.Model):
    IS_CHOOES = ((1, '显示到主页'), (0, '不显示到主页'))
    img = models.ImageField(upload_to="blog", verbose_name='上传图片')
    text = RichTextUploadingField(verbose_name='图片文字', default=' ')
    chooes = SmallIntegerField(choices=IS_CHOOES, verbose_name='图片是否显示在主页')

    class Meta:
        verbose_name = '主页图片展示'
        verbose_name_plural = verbose_name
Beispiel #25
0
class Topic(Model):
    title = CharField(max_length=100, unique=True)
    order_no = SmallIntegerField(default=100)
    created_at = DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['order_no', 'title']

    def __str__(self):
        return self.title
Beispiel #26
0
class MenuItem(Model):
    m = ForeignKey(Menu)
    name = CharField(
        max_length=100,
        db_index=True,
        verbose_name=_(u'Displayed \
		name'),
        help_text=_(u'Required field, max 100 characters. This is the \
		text to be shown in the menu.'))
    url = URLField(
        max_length=255,
        verbose_name=_(u'URL'),
        help_text=_(u'Optional field, max 255 characters. The target for the \
		menu item anchor.'),
        blank=True)
    parent = ForeignKey(
        'self',
        blank=True,
        null=True,
        related_name='children',
        help_text=_(
            u'If this item should be displayed in the dropdown, please \
		select its parent; optional filed.'))
    nofollow = BooleanField(default=False,
                            help_text=_(u'Check to add a nofollow\
	 value to the attribute "rel"; this attribute instructs web spiders to \
	ignore the target of the link; it is usually used for external pages.'))
    blank = BooleanField(
        default=False,
        verbose_name=_(u'Open in a new tab'),
        help_text=_(u'Check if you want the target page to be opened in a new\
		tab/window.'))
    o = SmallIntegerField(
        blank=True,
        null=True,
        verbose_name=_(u'Order'),
        help_text=_(
            u'Optional field, only numeric values allowed. Defines the \
		order of the item in the menu.'))
    active = BooleanField(default=True,
                          db_index=True,
                          help_text=_(u'Uncheck \
		if you want the item to disappear from the menu; ir can be reactivated\
		 at any time by checking this checbox.'))

    class Meta:
        verbose_name = u'Menu Item'
        verbose_name_plural = u'Menu Items'
        ordering = (
            'o',
            'id',
        )

    def __unicode__(self):
        return u'%s' % self.name
Beispiel #27
0
class Vote(Model):
    value = SmallIntegerField(null=False)
    create_date = DateTimeField(auto_now_add=True)
    user = ForeignKey(settings.AUTH_USER_MODEL,
                      null=True,
                      related_name='votes',
                      on_delete=SET_NULL)
    object_id = PositiveIntegerField(null=False)
    object_type = CharField(choices=VoteType.VARIANTS,
                            null=False,
                            max_length=1)
Beispiel #28
0
class User(Model):
    user_id = CharField(max_length=64)
    user_pet_name = CharField(max_length=64)
    iphone = CharField(max_length=16)
    email = CharField(max_length=64)
    password = CharField(max_length=255)
    age = SmallIntegerField()
    address = CharField(max_length=255)
    info = CharField(max_length=255)
    id = BigIntegerField(primary_key=True)

    # def to_dict(self):
    #     return json.dumps({
    #         'user_id': self.user_id,
    #         'user_pet_name': self.user_pet_name,
    #         'iphone': self.iphone,
    #         'email': self.email,
    #         'password': self.password,
    #         'age': self.age,
    #         'address': self.address,
    #         'info': self.info,
    #         'id': self.id,
    #     })
    def to_dict(self):
        return {
            'user_id': self.user_id,
            'user_pet_name': self.user_pet_name,
            'iphone': self.iphone,
            'email': self.email,
            'password': self.password,
            'age': self.age,
            'address': self.address,
            'info': self.info,
            'id': self.id,
        }

    def update_dict(self):
        return {
            user_id: username,
            user_pet_name: petname,
            iphone: iphone,
            email: email,
            password: password,
            age: age,
            address: address,
            info: info,
        }

    def __str__(self):
        ms = 'name:{}'.format(self.user_id)
        return ms

    class Meta():
        db_table = 'user'
Beispiel #29
0
class Vote(Model):
    LIKE = 1
    DISLIKE = -1

    VOTES = ((DISLIKE, 'Dislike'), (LIKE, 'Like'))

    vote = SmallIntegerField(verbose_name="vote", choices=VOTES)
    post = ForeignKey(Post, blank=False, null=False, on_delete=CASCADE)
    author = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE)

    objects = VoteManager()
Beispiel #30
0
    def __init__(self, *expressions, **extra):
        filter_exp = [
            Cast(exp, TextField()) for exp in expressions
            if isinstance(exp, str)
        ]
        if "output_field" not in extra:
            extra["output_field"] = SmallIntegerField()

        if len(expressions) < 2:
            raise ValueError("NotNullCount must take at least two expressions")

        super().__init__(*filter_exp, **extra)