示例#1
0
class FloorPass(models.Model):
    location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
    department = models.ForeignKey(Department,
                                   on_delete=models.CASCADE,
                                   null=True)
    supervisor_id = models.CharField(max_length=4, blank=True, null=True)
    supervisor_name = models.CharField(max_length=100, blank=True, null=True)
    purpose = models.TextField(blank=True, null=True)
    Status = models.IntegerChoices('Status', 'STAND_BY DEPARTED ARRIVED')
    status = models.IntegerField(choices=Status.choices, null=True)
    # latest_log_date = models.DateTimeField(blank=True, null=True)
    objects = models.Manager()

    @property
    def latest_log_date(self):
        log_count = len(self.log_set.all())
        if log_count == 0:
            return timezone.now().strftime("%m-%d %H:%M:%S")
        else:
            return self.log_set.all()[log_count -
                                      1].logdatetime.strftime("%m-%d %H:%M:%S")

    def status_label(self):
        if self.status is None:
            return ''
        else:
            return self.Status.choices[self.status][1]

    def current_location(self):
        if len(self.log_set.all()) == 0:
            return self.location.name
        else:
            return self.log_set.order_by('logdatetime')[0].location

    def timein(self):
        if len(self.log_set.all()) == 0:
            return ''
        else:
            return self.log_set.all()[0].logdatetime.strftime("%m-%d %H:%M:%S")

    def timeout(self):
        log_count = len(self.log_set.all())
        if log_count <= 1:
            return ''
        elif log_count > 1 and self.location.name == self.log_set.all()[
                log_count - 1].location:
            return self.log_set.all()[log_count -
                                      1].logdatetime.strftime("%m-%d %H:%M:%S")

    def time_elapse(self):
        log_count = len(self.log_set.all())
        if log_count <= 1:
            return ''
        else:
            return str(self.log_set.all()[log_count - 1].logdatetime -
                       self.log_set.all()[0].logdatetime).split(".")[0]

    def completed(self):
        return len(self.log_set.all()
                   ) == 0 and self.location == self.current_location(self)
示例#2
0
class Weekday(models.Model):
    Week = models.IntegerChoices(
        'Week', 'Monday Tuesday Wednesday Thursday Friday Saturday Sunday')
    days = models.SmallIntegerField(choices=Week.choices, unique=True)

    def __str__(self):
        return f' {self.get_days_display()} '
示例#3
0
class Journal(OwnerModel):
    tv_series = models.ForeignKey(TVSeries, on_delete=models.PROTECT, verbose_name='TV series')

    class Status(models.IntegerChoices):
        WATCHING = 1
        WAITING = 2
        DONE = 3
        STOPPED = 4
        DIDNT_WATCH = 5

    status = models.PositiveIntegerField(choices=Status.choices, default=Status.DIDNT_WATCH)

    last_watched_season = models.PositiveIntegerField(null=True, blank=True)
    last_watched_episode = models.PositiveIntegerField(null=True, blank=True)
    last_watched_date = models.DateField(null=True, blank=True)

    Rating = models.IntegerChoices('TV Series rating', '1 2 3 4 5')
    rating = models.PositiveIntegerField(choices=Rating.choices, null=True, blank=True)

    comment = models.TextField(blank=True)

    def __str__(self):
        return str(self.tv_series)

    class Meta:
        unique_together = [
            ['owner', 'tv_series']
        ]
        verbose_name = 'TV series entry'
        verbose_name_plural = 'TV series entries'
示例#4
0
class RegularPlan(models.Model):

  Unit_types = models.IntegerChoices('UnitType', 'kwh min')
  Cycle_types = models.IntegerChoices('CycleType',  'daily weekly')
  Tariff_types = models.IntegerChoices('TariffType','bi-time tri-time simple')

  name = models.CharField(max_length=100, null=False, blank=False)
  tar_included = models.BooleanField()
  subscription = models.FloatField(null=False, blank=False, validators=[validate_bigger_than_zero])
  cycle = models.IntegerField(null=False, blank=False, choices=Cycle_types.choices)
  type = models.IntegerField(null=False, blank=False, choices=Tariff_types.choices)
  offer_iva = models.BooleanField()
  off_peak_price = models.FloatField(null=False, blank=False, validators=[validate_bigger_than_zero])
  peak_price = models.FloatField(null=False, blank=False, validators=[validate_bigger_than_zero])
  unit = models.IntegerField(null=False, blank=False, choices=Unit_types.choices)
  valid = models.BooleanField()
  publish = models.BooleanField()
  vat = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)])

  owner = models.ForeignKey(User,null=True, on_delete=models.SET_NULL, blank=True)
示例#5
0
class Business(models.Model):
    name = models.CharField(max_length=30)
    category = models.IntegerChoices(choicdes=CategoryChoice.choices)

    # Address info
    # todo: table for cities etc?
    country = models.IntegerField()  # ICAO country code. (Which format?)
    city = models.CharField(max_length=30)
    street = models.CharField(max_length=50)
    address_num = models.CharField(max_length=30)
    postal_code = models.CharField(max_length=30)
示例#6
0
 def test_do_not_call_in_templates_member(self):
     # do_not_call_in_templates is not implicitly treated as a member.
     Special = models.IntegerChoices('Special', 'do_not_call_in_templates')
     self.assertEqual(
         Special.do_not_call_in_templates.label,
         'Do Not Call In Templates',
     )
     self.assertEqual(Special.do_not_call_in_templates.value, 1)
     self.assertEqual(
         Special.do_not_call_in_templates.name,
         'do_not_call_in_templates',
     )
示例#7
0
class Review(models.Model):
    """Handle Reviews in the system"""
    course = models.ForeignKey(
        Course,
        on_delete=models.CASCADE,
    )

    reviewer_name = models.CharField(max_length=255)
    score = models.IntegerChoices('score', 'Hate Dislike Ok Like Love')
    content = models.CharField(max_length=255)

    def __str__(self):
        """Return string representation of the model"""
        return self.content
示例#8
0
class Journal(OwnerModel):
    book = models.ForeignKey(Book, on_delete=models.PROTECT)
    source = models.ForeignKey(Source, on_delete=models.PROTECT, null=True, blank=True)

    class Status(models.IntegerChoices):
        DIDNT_READ = 1
        READING = 2
        DONE = 3
        STOPPED = 4

    status = models.PositiveIntegerField(choices=Status.choices, default=Status.DIDNT_READ)

    add_date = models.DateField(default=timezone.now, null=True)
    start_date = models.DateField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)
    pages_number = models.PositiveIntegerField(null=True, blank=True)

    Rating = models.IntegerChoices('Book rating', '1 2 3 4 5')
    rating = models.PositiveIntegerField(choices=Rating.choices, null=True, blank=True)

    note = models.TextField(blank=True)

    @property
    def days_spent(self):
        empty = settings.EMPTY_VALUE_DISPLAY
        if self.status == Journal.Status.DIDNT_READ or self.status == Journal.Status.STOPPED:
            return empty

        start_date = self.start_date
        end_date = self.end_date

        if self.status == Journal.Status.READING:
            end_date = timezone.now().date()

        if end_date is None or start_date is None:
            return empty

        return (end_date - start_date).days

    def __str__(self):
        return str(self.book)

    class Meta:
        unique_together = [
            ['owner', 'book']
        ]
        verbose_name = 'book entry'
        verbose_name_plural = 'book entries'
示例#9
0
文件: models.py 项目: SGaidi/MessageU
class Message(models.Model):

    MessageType = models.IntegerChoices(
        value='MessageType',
        names=[(str(t), t) for t in ALL_REQUEST_MESSAGES_TYPES],
    )

    to_client = models.ForeignKey(Client,
                                  related_name='waiting_messages',
                                  help_text="The message recipient",
                                  on_delete=models.CASCADE)
    from_client = models.ForeignKey(Client,
                                    related_name='sent_messages',
                                    help_text="The message sender",
                                    on_delete=models.CASCADE)
    # did not use `type` name because it's a Python built-in
    message_type = models.IntegerField(choices=MessageType.choices)
    content = models.BinaryField(help_text="The message content")
示例#10
0
class Product(models.Model):
    """Products"""
    user = models.ForeignKey(StaffUser, on_delete=models.SET_NULL, null=True)
    title = models.CharField(max_length=255)
    image = models.ImageField(null=True,
                              blank=True,
                              upload_to='images/products')
    description = models.TextField(blank=True)
    price = models.IntegerField(blank=True, null=True)
    category = models.ForeignKey(Category,
                                 on_delete=models.SET_NULL,
                                 null=True,
                                 related_name='products')
    subcategory = models.ForeignKey(Subcategory,
                                    on_delete=models.SET_NULL,
                                    null=True,
                                    related_name='products')
    brand = models.ForeignKey(Brand,
                              on_delete=models.SET_NULL,
                              null=True,
                              related_name='products')
    discount = models.ManyToManyField(ItemDiscount, related_name='products')
    condition = models.IntegerChoices('condition', '1 2 3 4 5 6 7 8 9 10')
    purchase_price = models.IntegerField(blank=True, null=True)
    pledge = models.IntegerField(blank=True, null=True)
    city = models.ForeignKey(City,
                             on_delete=models.SET_NULL,
                             null=True,
                             related_name='products')
    inside_city = models.IntegerField(blank=True,
                                      null=True,
                                      verbose_name='price within the city')
    outside_city = models.IntegerField(blank=True,
                                       null=True,
                                       verbose_name='price within the city')
    delivery = models.IntegerField(blank=True,
                                   null=True,
                                   verbose_name='delivery price')
    pickup = models.CharField(max_length=800,
                              blank=True,
                              verbose_name='pickup address')

    def __str__(self):
        return self.title
示例#11
0
class Collection(models.Model):
    FetchingStatus = models.IntegerChoices('FetchingStatus',
                                           'STARTED FINISHED FAILED')

    name = models.CharField(max_length=36,
                            default=uuid4,
                            unique=True,
                            blank=False,
                            editable=False)
    created = models.DateTimeField(auto_now_add=True,
                                   blank=False,
                                   editable=False)
    modified = models.DateTimeField(auto_now=True, blank=False, editable=False)
    fetching_status = models.IntegerField(default=FetchingStatus.STARTED,
                                          choices=FetchingStatus.choices,
                                          blank=False,
                                          editable=False)

    def age(self):
        return (now() - self.created).total_seconds()
示例#12
0
class Listing(models.Model):
    Direction = models.IntegerChoices('Direction', 'BUY SELL')
    int_to_direction = {k: v for k, v in Direction.choices}

    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    count = models.IntegerField()
    price = models.IntegerField()
    direction = models.IntegerField(choices=Direction.choices)
    submitter = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.item.name}-{self.count}-{self.price}-{self.int_to_direction[self.direction]}-{self.submitter}'

    def description(self):
        return f'{self.count} of "{self.item}" for {self.price} coins'

    @transaction.atomic
    def process_purchase(self, count):
        if self.direction != Listing.Direction.SELL:
            raise InvalidTransactionError()
        if count > self.count:
            raise ValueError("Cannot take more items than listed")
        wallet = Wallet.get_users_wallet(self.submitter)
        wallet.add(self.price * count)
        self.count -= count
        if not self.count:
            self.delete()
        else:
            self.save()

    @transaction.atomic
    def cancel(self):
        if self.direction == Listing.Direction.BUY:
            wallet = Wallet.get_users_wallet(self.submitter)
            wallet.add(self.price * self.count)
        else:
            self.item.add_to_user_inventory(self.submitter, self.count)
        self.delete()
示例#13
0
 def test_integerchoices_functional_api(self):
     Place = models.IntegerChoices("Place", "FIRST SECOND THIRD")
     self.assertEqual(Place.labels, ["First", "Second", "Third"])
     self.assertEqual(Place.values, [1, 2, 3])
     self.assertEqual(Place.names, ["FIRST", "SECOND", "THIRD"])
示例#14
0
"""Django models for the jugemaj app."""
from functools import cmp_to_key

from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.urls import reverse
from ndh.models import NamedModel, TimeStampedModel

# ref https://github.com/typeddjango/django-stubs/issues/729
CHOICES = models.IntegerChoices(
    "choix", "Super Bien OK Passable Insuffisant Nul")  # type: ignore


def sort_candidates(a, b):
    """
    Sort candidates a & b by their majority gauge.

    - α is the majority grade;
    - p the percentage of votes strictly above α;
    - q the percentage of votes strictly below α.

    a > b ⇔ a_α > b_α || (a_α == b_α && (a_p > max(a_q, b_p, b_q) || b_q > max(a_p, a_q, b_p)))

    (ref eq. 2, p.11 of the second article in README.md)
    """
    (a_p, a_α, a_q), (b_p, b_α, b_q) = a.majority_gauge(), b.majority_gauge()
    if a_α > b_α:
        return 1
    if b_α > a_α:
示例#15
0
class Comment(BasicModel):
    id = models.AutoField(primary_key=True)
    movie_id = models.IntegerField
    context = models.TextField
    checked = models.IntegerChoices('0', '1')
示例#16
0
 def test_integerchoices_functional_api(self):
     Place = models.IntegerChoices('Place', 'FIRST SECOND THIRD')
     self.assertEqual(Place.labels, ['First', 'Second', 'Third'])
     self.assertEqual(Place.values, [1, 2, 3])
     self.assertEqual(Place.names, ['FIRST', 'SECOND', 'THIRD'])
示例#17
0
文件: models.py 项目: elmasta/VGS
    BON = 4, gettext_lazy("Bon")
    TRES_BON = 5, gettext_lazy("Très Bon")
    NEUF = 6, gettext_lazy("Neuf")


class Owning(models.IntegerChoices):

    POSSEDE = 1, gettext_lazy("Possédé")
    VENDU = 2, gettext_lazy("Vendu")
    DONNE = 3, gettext_lazy("Donné")
    PRET_D_UN_AMI = 4, gettext_lazy("Pret d'un ami")
    ABONNEMENT = 5, gettext_lazy("Abonnement")
    AUTRE = 6, gettext_lazy("Autre")


RATING = models.IntegerChoices("RATING", "0 1 2 3 4 5 6 7 8 9 10")

ELEM = [
    "Europe", "Amérique du Nord", "Japon", "Amérique central",
    "Emérique du Sud", "Asie", "Russie", "Moyen Orient", "Afrique", "Monde"
]


class UserData(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profil_picture = models.ImageField(upload_to=get_userpic_path,
                                       blank=True,
                                       null=True,
                                       validators=[validate_picture])
    created_at = models.DateTimeField(auto_now_add=True)
示例#18
0
from django.db import models
from django.template import loader
from django.db.models import Q
from uuid import uuid1

# Document visibility enumeration.
Visibility = models.IntegerChoices('Visibility', 'PUBLIC PROTECTED PRIVATE')


class Tag(models.Model):
    'A tag which can be attributed to documents, on a many-to-one basis.'
    tag_name = models.CharField(max_length = 32)
    def __str__(self):
        return self.tag_name

class DocumentCategory(models.Model):
    '''
    A category for documents.
    Replaces the previous enum.
    '''
    name = models.CharField(max_length = 32, unique = True)
    def __str__(self):
        return self.name

class Document(models.Model):
    '''
    A representation of input Documents.
    These could be portfolio pieces, education, or other media for representing the user.
    '''
    document_name = models.CharField(max_length = 128)
    document_type = models.ForeignKey(DocumentCategory, null = True, on_delete = models.PROTECT)
示例#19
0
class ItemPage(models.Model):
    objects: models.QuerySet

    class Meta:
        db_table = 'item_page'

    id = models.AutoField(primary_key=True)
    item = models.ForeignKey(
        Item,
        related_name='itemPages',
        on_delete=models.DO_NOTHING, )
    volume: Volume = models.ForeignKey(
        Volume,
        related_name='volumeItemPages',
        on_delete=models.DO_NOTHING,
        null=True)
    # A few page numbers may be Roman numerals, have letter suffix, etc.
    page = models.CharField('page number', max_length=20)
    date: datetime.date = models.DateField(
        'date of mention',
        null=True,
        blank=True,
        # default=datetime.date.today,
    )
    year = models.IntegerField(
        'year of mention',
        null=True,
        blank=True,
    )
    month = models.IntegerField(
        'month of mention',
        choices=models.IntegerChoices(
            'month',
            calendar.month_abbr[1:]).choices,
        null=True,
        blank=True,
    )

    @property
    def url(self):
        # TODO: get the host and base URL from app config
        return self.volume.makeUrl(self.page)

    url.fget.short_description = 'Library URL for volume with page'

    @property
    def dateCalc(self) -> Optional[str]:
        """
        use date if specified, otherwise make one from year/month,
        else return `None`

        :return: str "Mon YYYY" or none
        """
        if self.date:
            result = self.date.strftime('%b %Y')
        elif self.year and self.month:
            result = f'{calendar.month_abbr[self.month]} {self.year}'
        else:
            result = None

        return result

    def __str__(self):
        return f'Page: {self.page} {self.date}'
示例#20
0
from cl.lib.models import AbstractDateTimeModel


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)


class WebhookEventType(models.IntegerChoices):
    RECAP_EMAIL = 1, "RECAP email received"
    ALERT = 2, "Alert triggered"


HttpStatusCodes = models.IntegerChoices(  # type: ignore
    "HttpStatusCodes", [(s.name, s.value) for s in HTTPStatus]
)


class Webhook(AbstractDateTimeModel):
    user = models.ForeignKey(
        User,
        help_text="The user that has provisioned the webhook.",
        related_name="webhooks",
        on_delete=models.CASCADE,
    )
    event_type = models.IntegerField(
        help_text="The event type that triggers the webhook.",
        choices=WebhookEventType.choices,
    )
    url = models.URLField(
示例#21
0
class Rate(models.Model):
    rate = models.IntegerChoices(null=True, blank=True)

    def __str__(self):
        return str(self.rate)
示例#22
0
class User(models.Model):
    employee_id = models.CharField(max_length=4, primary_key=True, unique=True)
    employee_name = models.TextField(null=True)

    floorpasses = models.ManyToManyField(FloorPass)

    Status = models.IntegerChoices('Status', 'STAND_BY DEPARTED ARRIVED')
    status = models.IntegerField(choices=Status.choices, default=0, null=True)
    last_modified = models.DateTimeField(auto_now=datetime.datetime.now,
                                         null=True)

    @property
    def last_modified_ph(self):
        return (self.last_modified + timedelta(hours=8))

    @property
    def latest_log_date(self):
        log_count = len(self.log_set.all())
        if log_count == 0:
            return (self.last_modified +
                    timedelta(hours=8)).strftime("%Y-%m-%d %I:%M:%S %p")
        else:
            return self.log_set.all()[log_count - 1].logdatetime_str()

    def status_label(self):
        if self.status is None:
            return ''
        else:
            return self.Status.choices[self.status][1]

    def current_location(self):
        if len(self.log_set.all()) == 0:
            return self.location.name
        else:
            return self.log_set.order_by('logdatetime')[0].location

    def completed(self):
        return len(self.log_set.all()
                   ) == 0 and self.location == self.current_location(self)

    def report(self, floorpass_id):
        # return [{'dada': 'dada'}]
        destinations = []
        destination = {}
        for l in self.log_set.filter(floorpass=floorpass_id):
            if destination == {}:
                destination['from'] = {'loc': l.location, 'at': l.logdatetime}
                if len(destinations) > 0:
                    prevdes = destinations[-1]
                    p2pelapse = {
                        'from': prevdes['to'],
                        'to': destination['from']
                    }
                    p2pelapse['elapse'] = str(p2pelapse['to']['at'] -
                                              p2pelapse['from']['at']).split(
                                                  '.')[0]
                    destinations.append(p2pelapse)
            else:
                destination['to'] = {'loc': l.location, 'at': l.logdatetime}
                destination['elapse'] = str(destination['to']['at'] -
                                            destination['from']['at']).split(
                                                '.')[0]
                destinations.append(destination)
                destination = {}

        return destinations

    def reports(self, datefrom):
        reports = []
        floorpasses = self.floorpasses.all().order_by('-date_created')
        if datefrom != '':
            floorpasses = self.floorpasses.filter(
                date_created__gte=datefrom).order_by('-date_created')
        for u in floorpasses:
            reports.append({
                'reference_id': u.reference_id,
                'report': self.report(u)
            })

        return reports
示例#23
0
class Image(models.Model):
    image = ImageField(manualcrop="700x700")
    likes =  models.IntegerChoices()
示例#24
0
文件: models.py 项目: AntXinyuan/XDOJ
from django_mysql.models import JSONField
from django.db import models
from account.models import User
from django.utils.translation import gettext_lazy as _
from judger.judger import JudgeStatus

# 因为jsonField的默认值只能为不可变量,所以初始化的工作放到了views.py中进行!!!
init_statistic_info = JudgeStatus.count_dict()
Difficulty = models.IntegerChoices('Difficulty', 'Low Mid High')


class JudgeMode(models.TextChoices):
    standard = 'Stardand', _('标准')
    cumulative = 'Cumulative', _('累加')


class ProblemTag(models.Model):
    name = models.CharField(max_length=10, db_index=True)

    class Meta:
        db_table = "problem_tag"
        verbose_name = '题目标签'
        verbose_name_plural = '题目标签'

    def __str__(self):
        return self.name


class Problem(models.Model):
    title = models.CharField('标题', max_length=32)
    description = models.TextField('问题描述', max_length=512)