Exemplo n.º 1
0
 def get_length_of_stay_per_day(self, start_date, end_date):
     return self.attendance_set.filter(
         sign_in__lte=end_date, sign_in__gte=start_date).annotate(
             length_of_stay=Coalesce(
                 'sign_out',
                 Cast(F('sign_in') + timedelta(hours=8), DateTimeField())) -
             F('sign_in'),
             day_of_work=Cast('sign_in', DateField())).values(
                 'day_of_work').order_by('day_of_work').annotate(
                     stay_per_day=Sum('length_of_stay'))
Exemplo n.º 2
0
 def qs_with_publication_date(queryset: QuerySet,
                              channel_slug: str) -> QuerySet:
     validate_channel_slug(channel_slug)
     subquery = Subquery(
         ProductChannelListing.objects.filter(
             product_id=OuterRef("pk"),
             channel__slug=channel_slug).values_list("publication_date")
         [:1])
     return queryset.annotate(publication_date=ExpressionWrapper(
         subquery, output_field=DateField()))
Exemplo n.º 3
0
class Movie(Model):
    title = CharField(max_length=128)
    genre = ForeignKey(Genre, on_delete=DO_NOTHING)
    rating = IntegerField()
    released = DateField()
    description = TextField()
    created = DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title
Exemplo n.º 4
0
class Admin(Model):
    date = DateField(max_length=255,
                     blank=True,
                     default=datetime.now,
                     null=True)
    version = CharField(max_length=255, blank=True, default=None, null=True)

    class Meta:
        app_label = 'db'
        db_table = 'admin'
Exemplo n.º 5
0
class Record(models.Model):
    date        = DateField()
    description = CharField(max_length=300)
    category    = ForeignKey(Category , on_delete=models.SET_NULL,null=True)
    cash        = IntegerField()
    balance_type= CharField(max_length=2,choices=BALANCE_TYPE)     #收支
    def __str__(self):
        return  self.description +' ('+ str(self.date) +')'
#model建立完要到admin註冊
    '''
Exemplo n.º 6
0
class Answer(BaseModel):
    date = DateField()
    id = CharField(max_length=20, primary_key=True)
    profile = ForeignKey(Profile, related_name='answers', on_delete=CASCADE)
    question = ForeignKey(Question, related_name='answers', on_delete=CASCADE)
    text = TextField()
    vote_count = IntegerField()

    def __str__(self):
        return f'[{self.id}] {self.text}'
Exemplo n.º 7
0
class Profile(TimeStamped):
    user = OneToOneField("auth.User")
    date_of_birth = DateField(null=True)

    def __str__(self):
        return self.user.username

    class Meta:
        verbose_name = _("Profile")
        verbose_name_plural = _("Profiles")
class Diagnosismodel(models.Model):
    Diagnosis_ID=IntegerField(primary_key=True)
    Date=DateField()
    Diagnosis_details=CharField(max_length=300)
    Remarks=CharField(max_length=300)
    Prescription=CharField(max_length=300)
    Insurance_Policy_No=CharField(max_length=300)
    Patient_Id=IntegerField()
    class Meta:
        db_table='patient_diagnosis'
class patient_doctor(models.Model):
    Patient_Id=IntegerField()
    Patient_Name=CharField(max_length=300)
    Appointment_Date=DateField()
    Time=CharField(max_length=300)
    Purpose=CharField(max_length=300)
    Patient_Contact_No=CharField(max_length=10)
    Doctor_Id=IntegerField()
    Doctor_Name=CharField(max_length=300)
    Room_No=IntegerField()
Exemplo n.º 10
0
class InflowTransaction(TimeStampedModel):
    clinic = ForeignKey(Clinic, on_delete=PROTECT)
    amount = DecimalField(max_digits=8, decimal_places=2)
    payment_holder = CharField('Titular do Pagamento', max_length=25)
    service_beneficiary = CharField('Beneficiário do Serviço',
                                    blank=True,
                                    max_length=25)
    description = CharField('Descrição', max_length=255)
    date = DateField('Data')
    type = ForeignKey(TransactionType, on_delete=PROTECT)
Exemplo n.º 11
0
class Recipe(Model):
    name = CharField(max_length=100, help_text='The name of the recipe.')
    slug = AutoSlugField(_('slug'),
                         editable=True,
                         unique=True,
                         populate_from='name',
                         help_text='An easy-to-remember short name.')
    uuid = UUIDField(editable=False, default=uuid.uuid4, primary_key=True)
    language = CharField(max_length=20,
                         choices=[('en', 'english'), ('sv', "swedish")],
                         default='english')

    makes = CharField(
        max_length=100,
        help_text='How much the recipe yields, for 4 people, 8 pieces, etc.')

    description = TextField(blank=True, null=True)

    external_recipes = ManyToManyField('Recipe', blank=True)

    cooking_time = DurationField(blank=True, null=True)
    temperature = IntegerField(blank=True, default=0)

    ingredients = JSONField()
    instructions = JSONField()

    changelog = JSONField(blank=True)
    notes = ArrayField(TextField(), null=True)
    tips = ArrayField(TextField(), null=True)

    pub_date = DateField('date_published',
                         default=timezone.now,
                         editable=False)
    last_changed = DateField(default=timezone.now)

    # image = ImageField(upload_to='images/')

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']
        verbose_name_plural = 'recipes'
Exemplo n.º 12
0
class ExternalMailingListSubscriber(models.Model):
    email = EmailField(blank=False)
    subscription_date = DateField()

    def __str__(self):
        return self.email

    def postsave(self):
    # send email after save
        return
Exemplo n.º 13
0
class TestModel(Model):
    foo = IntegerField(null=True)
    bar = IntegerField(default=1)
    created_at_date = DateField(auto_now=True)
    created_at = DateTimeField(auto_now=True)
    fk = ForeignKey('TestModel2', null=True, related_name='fks')
    one2one = OneToOneField('TestModel2', null=True, related_name='one2ones')

    def __repr__(self):
        return '<TestModel (#%d): foo=%d>' % (self.pk, self.foo)
Exemplo n.º 14
0
 def __count_per_date(self, date_):
     # We need an order_by here because Sample class has a default order_by. See:
     # https://docs.djangoproject.com/en/2.1/topics/db/aggregation/#interaction-with-default-ordering-or-order-by
     return self.annotate(date=Trunc(date_, 'day', output_field=DateField(
     ))).values('date').annotate(count=Count('*')).order_by()
     count_dict = {}
     for element in counts:
         if element['date'] is not None:
             count_dict[element['date']] = element['count']
     return count_dict
Exemplo n.º 15
0
class Blog(models.Model):
    title = CharField(max_length=250)
    date = DateField()
    banner = ImageField(upload_to='static/images/article', default='static/images/article/default.jpg')
    thumbnail = ImageField(upload_to='static/images/article', default='static/images/article/default.jpg')
    short_content = TextField(default='such empty...')
    content = TextField()

    def __str__(self):
        return self.title[:100]
Exemplo n.º 16
0
class Diagnosis(Model):
    doctor = ForeignKey(Doctor, related_name="diagnosis")
    patient = ForeignKey(Profile, related_name="Patient")
    record_book = ForeignKey(MedicalRecordBook, related_name="diagnosis")
    medicine = ManyToManyField(Medicine, through="Prescription")
    diagnosis_date = DateField()
    syptom = TextField()

    def __str__(self):
        return self.syptom
Exemplo n.º 17
0
class ModelWithWrongFieldOrder(Model):
    """
    >>> a = ModelWithWrongFieldOrder(slug='test')
    >>> a.save()
    Traceback (most recent call last):
    ...
    ValueError: Could not check uniqueness of ModelWithWrongFieldOrder.slug with respect to ModelWithWrongFieldOrder.date because the latter is empty. Please ensure that "slug" is declared *after* all fields listed in unique_with.
    """
    slug = AutoSlugField(unique_with='date')
    date = DateField(blank=False, null=False)
class PaymentRecord(Model):
    chitbatch = ForeignKey(ChitBatch,
                           related_name='payments',
                           on_delete="CASCADE")
    member = ForeignKey(Member, related_name='payments', on_delete="CASCADE")
    paid = IntegerField(blank=True,
                        null=True,
                        default=PaymentRecordEnum.PAID,
                        choices=PaymentRecordEnum.CHOICES)
    bid_date = DateField(blank=False)
Exemplo n.º 19
0
class Record(models.Model):
    #user = CharField(max_length=10)
    date = DateField()
    description = CharField(max_length=300)
    category = ForeignKey(Category, on_delete=models.SET_NULL, null=True)
    cash = IntegerField()
    balance_type = CharField(max_length=2, choices=BALANCE_TYPE)

    def __str__(self):
        return self.description
Exemplo n.º 20
0
def read_entry(body, donations):
    body = unidecode(body.lower())

    equation = re.search(
        '(\d+)(?:\s*ml)*((?:\s*-\s*\d+(?:\s*ml)*)*)\s*=\s*(\d+)(?:\s*ml)*',
        body.replace(" ", ""), re.MULTILINE | re.DOTALL)

    dates = re.search(
        'dat[ay](?: donacji)?:\s*(\d{4}[-\.]\d{1,2}[-\.]\d{1,2}(?:\s*,\s*\d{4}[-\.]\d{1,2}[-\.]\d{1,2})*)',
        body, re.MULTILINE | re.DOTALL)

    types = re.search(
        'skladniki?:\s*((?:krew|plytki|osocze)(?:\s*,\s*(?:krew|plytki|osocze))*)',
        body, re.MULTILINE | re.DOTALL)

    if equation:
        base = int(equation.group(1))
        ds = equation.group(2).replace("ml", "").strip("- ").split("-")
        donation_values = [int(dv.strip()) for dv in ds]
        result = int(equation.group(3))

        print "%d - %d = %d" % (base, sum(donation_values), result)

        if base - sum(donation_values) != result:
            print "Error"

        if not donations:
            for dv in donation_values:
                donations.append({"value": dv})
        else:
            for dv, i in zip(donation_values, range(len(donation_values))):
                if len(donations) <= i:
                    donations.append({"value": dv})
                else:
                    donations[i]["value"] = dv

        for donation in donations:
            for type, ml in DONATION_TYPE:
                if donation["value"] == ml:
                    donation["type"] = type

    if dates:
        donation_dates = dates.group(1).split(",")
        for date, i in zip(donation_dates, range(len(donation_dates))):
            date = date.replace(".", "-")
            donations[i]["date"] = str(DateField().to_python(date.strip()))

    if types:
        trl = {"krew": "Blood", "plytki": "Platelets", "osocze": "Plasma"}
        donation_types = types.group(1).split(",")
        for type, i in zip(donation_types, range(len(donation_types))):
            donations[i]["type"] = trl[type.strip()]

    for donation in donations:
        print str(donation)
Exemplo n.º 21
0
class BaseAttribute(Model):
    """ Base class for choices.  Concrete choice class must overload the
    `schema` and `choice` attributes.
    """
    entity_type = ForeignKey(ContentType)
    entity_id = IntegerField()
    entity = GenericForeignKey(ct_field="entity_type", fk_field='entity_id')

    value_text = TextField(blank=True, null=True)
    value_float = FloatField(blank=True, null=True)
    value_date = DateField(blank=True, null=True)
    value_bool = NullBooleanField(
        blank=True)  # TODO: ensure that form invalidates null booleans (??)
    value_range_min = FloatField(blank=True, null=True)
    value_range_max = FloatField(blank=True, null=True)

    schema = NotImplemented  # must be FK
    choice = NotImplemented  # must be nullable FK

    class Meta:
        abstract = True
        verbose_name, verbose_name_plural = _('attribute'), _('attributes')
        ordering = ['entity_type', 'entity_id', 'schema']
        unique_together = ('entity_type', 'entity_id', 'schema', 'choice')

    def __unicode__(self):
        return u'%s: %s "%s"' % (self.entity, self.schema.title, self.value)

    def _get_value(self):
        if self.schema.datatype in (self.schema.TYPE_ONE,
                                    self.schema.TYPE_MANY):
            return self.choice
        if self.schema.datatype == self.schema.TYPE_RANGE:
            names = ('value_range_%s' % x for x in ('min', 'max'))
            value = tuple(getattr(self, x, None) for x in names)
            return None if value == (None, None) else value
        return getattr(self, 'value_%s' % self.schema.datatype)

    def _set_value(self, new_value):
        if self.schema.datatype == self.schema.TYPE_RANGE:
            new_value = new_value or (None, None)

            # validate range value -- expecting a tuple of two numbers
            try:
                validate_range_value(new_value)
            except (TypeError, ValueError):
                raise

            for k, v in zip('min max'.split(), new_value):
                v = v if v is None else float(v)
                setattr(self, 'value_range_%s' % k, v)
        else:
            setattr(self, 'value_%s' % self.schema.datatype, new_value)

    value = property(_get_value, _set_value)
Exemplo n.º 22
0
class ExternalVideo(ExternalContent):
    resource_type = "video"
    is_external = True

    # Meta fields
    date = DateField(
        "Video date",
        default=datetime.date.today,
        help_text="The date the video was published",
    )
    speakers = StreamField(
        StreamBlock(
            [("speaker", PageChooserBlock(target_model="people.Person"))],
            required=False,
        ),
        blank=True,
        null=True,
        help_text="Optional list of people associated with or starring in the video",
    )
    duration = CharField(
        max_length=30,
        blank=True,
        null=True,
        help_text=(
            "Optional video duration in MM:SS format e.g. “12:34”. "
            "Shown when the video is displayed as a card"
        ),
    )

    meta_panels = [
        FieldPanel("date"),
        StreamFieldPanel("speakers"),
        InlinePanel("topics", heading="Topics"),
        FieldPanel("duration"),
    ]

    settings_panels = BasePage.settings_panels + [FieldPanel("slug")]

    edit_handler = TabbedInterface(
        [
            ObjectList(ExternalContent.card_panels, heading="Card"),
            ObjectList(meta_panels, heading="Meta"),
            ObjectList(settings_panels, heading="Settings", classname="settings"),
        ]
    )

    @property
    def video(self):
        return self

    def has_speaker(self, person):
        for speaker in self.speakers:  # pylint: disable=not-an-iterable
            if str(speaker.value) == str(person.title):
                return True
        return False
Exemplo n.º 23
0
class Post(Model):
    """Blog post; news article about startups"""

    title = CharField(max_length=63)
    slug = SlugField(
        max_length=63,
        help_text="A label for URL config",
        unique_for_month="pub_date",
    )
    text = TextField()
    pub_date = DateField("date published", default=date.today)
    tags = ManyToManyField(Tag, related_name="blog_posts")
    startups = ManyToManyField(Startup, related_name="blog_posts")

    class Meta:
        get_latest_by = "pub_date"
        ordering = ["-pub_date", "title"]
        verbose_name = "blog post"

    def __str__(self):
        date_string = self.pub_date.strftime("%Y-%m-%d")
        return f"{self.title} on {date_string}"

    def get_absolute_url(self):
        """Return URL to detail page of Post"""
        return reverse(
            "post_detail",
            kwargs={
                "year": self.pub_date.year,
                "month": self.pub_date.month,
                "slug": self.slug,
            },
        )

    def get_update_url(self):
        """Return URL to update page of Post"""
        return reverse(
            "post_update",
            kwargs={
                "year": self.pub_date.year,
                "month": self.pub_date.month,
                "slug": self.slug,
            },
        )

    def get_delete_url(self):
        """Return URL to delete page of Post"""
        return reverse(
            "post_delete",
            kwargs={
                "year": self.pub_date.year,
                "month": self.pub_date.month,
                "slug": self.slug,
            },
        )
Exemplo n.º 24
0
class AbstractPollCampaign(CremeEntity):
    name = CharField(_('Name'), max_length=100)
    goal = TextField(_('Goal of the campaign'), blank=True)
    start = DateField(_('Start'), null=True, blank=True)
    due_date = DateField(_('Due date'), null=True, blank=True)
    segment = ForeignKey(
        MarketSegment,
        verbose_name=_('Related segment'),
        null=True,
        blank=True,
        on_delete=PROTECT,
    )
    expected_count = PositiveIntegerField(_('Expected replies number'),
                                          default=1)

    creation_label = pgettext_lazy('polls', 'Create a campaign')
    save_label = pgettext_lazy('polls', 'Save the campaign of polls')

    class Meta:
        abstract = True
        # manager_inheritance_from_future = True
        app_label = 'polls'
        verbose_name = _('Campaign of polls')
        verbose_name_plural = _('Campaigns of polls')
        ordering = ('name', )

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('polls__view_campaign', args=(self.id, ))

    @staticmethod
    def get_create_absolute_url():
        return reverse('polls__create_campaign')

    def get_edit_absolute_url(self):
        return reverse('polls__edit_campaign', args=(self.id, ))

    @staticmethod
    def get_lv_absolute_url():
        return reverse('polls__list_campaigns')
Exemplo n.º 25
0
class Employee(Model):
    """
    Employee model for FiveStars internal directory
    """
    first_name = CharField("First Name", max_length=32, db_index=True)
    last_name = CharField("Last Name", max_length=32, db_index=True)
    dept = ForeignKey(Department)
    title = CharField(max_length=64)
    phone_num = CharField("Phone Number", max_length=12)
    location = ForeignKey(Location)
    email = CharField(max_length=64, unique=True)
    start_date = DateField("Start Date")
    birthday = DateField(null=True, blank=True)
    spirit_animal = CharField("Spirit Animal",
                              max_length=32,
                              null=True,
                              blank=True)
    buddy = CharField(max_length=32, null=True, blank=True)
    image_url = CharField("Image URL", max_length=256, null=True, blank=True)

    class Meta:
        ordering = ['first_name', 'last_name']

    def __unicode__(self):
        return "%s %s" % (self.first_name, self.last_name)

    @property
    def is_new(self):
        """
        Is the employee new, i.e. started within the past 30 days?
        :return: true if the employee is new; false otherwise
        """
        return (date.today() - self.start_date).days < 30

    @property
    def is_birthday_today(self):
        """
        Is the employee's birthday today?
        :return: true if the employee's birthday is today; false otherwise
        """
        return self.birthday.month == date.today(
        ).month and self.birthday.day == date.today().day
Exemplo n.º 26
0
class User(AbstractUser):

    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = CharField(
        _("Name of User"),
        max_length=255,
    )
    dob = DateField(
        "Date of Birth",
        null=True,
    )
    address = CharField(
        "Address",
        max_length=255,
        null=True,
    )
    town_or_city = CharField(
        "Town/City",
        max_length=64,
        null=True,
    )
    zipcode = CharField(
        "Zipcode/Postcode",
        max_length=32,
        null=True,
    )
    country = CountryField("Country", max_length=64)
    tax_residency = CharField(
        "Tax Residency",
        max_length=32,
        blank=True,
        null=True,
    )
    kyc_last_date = DateField(
        "Last KYC Check",
        blank=True,
        null=True,
    )

    def get_absolute_url(self):
        return reverse("users:detail", kwargs={"username": self.username})
Exemplo n.º 27
0
class Article(Model):
    STATUS_CHOICES = (('draft', 'draft'), ('public', 'public'), ('delete',
                                                                 'delete'))

    author = ForeignKey('auth.User')

    title = CharField(max_length=200)

    slug = SlugField(blank=True, editable=False)

    description = TextField(blank=True)

    text = RichTextField()

    created_at = DateField(default=timezone.now)

    public_at = DateField(blank=True, null=True)

    status = CharField(choices=STATUS_CHOICES, default='draft', max_length=10)

    city = ForeignKey('geo.City', null=True)

    media = ImageField(upload_to='media/%Y/%m/%d',
                       null=True,
                       blank=True,
                       help_text="Upload your photo for post")

    def update(self):
        if self.status == 'public':
            self.public_at = timezone.now
            self.save()

    def save(self, *args, **kwargs):
        self.slug = pytils.translit.slugify(self.title.lower())
        super(Article, self).save(*args, **kwargs)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Detail Article'
        verbose_name_plural = 'Article'
Exemplo n.º 28
0
class TruncDate(TruncBase):
    kind = 'date'
    lookup_name = 'date'
    output_field = DateField()

    def as_sql(self, compiler, connection):
        # Cast to date rather than truncate to date.
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql = connection.ops.datetime_cast_date_sql(lhs, tzname)
        return sql, lhs_params
Exemplo n.º 29
0
class OperationSystem(Model):
    name = StringField(_("Name"))
    family = FK(_("Family"), OperationSystemFamily)
    end_of_life = DateField(_("End of life"), null=True, blank=True)

    class Meta:
        verbose_name = _('Operation system')
        verbose_name_plural = _('Operation systems')

    def __str__(self):
        return "%s (%s)" % (self.name, self.family)
Exemplo n.º 30
0
class Contract(Auditable):

    apartment = ForeignKey(Apartment,
                           related_name='apartment_contracts',
                           on_delete=CASCADE)
    tenant = ForeignKey(Tenant,
                        related_name='tenant_contracts',
                        on_delete=CASCADE)
    start_date = DateField()
    end_date = DateField()
    remarks = TextField()
    rent_collection = CharField(max_length=100,
                                choices=[('month', 'Every Month'),
                                         ('2months', 'Every Two Months'),
                                         ('3months', 'Every Three Months'),
                                         ('6months', 'Every Six Months')])
    is_valid = BooleanField(default=True)

    class Meta:
        unique_together = ('apartment', 'tenant')
Exemplo n.º 31
0
    lookup_name = 'week_day'


class ExtractHour(Extract):
    lookup_name = 'hour'


class ExtractMinute(Extract):
    lookup_name = 'minute'


class ExtractSecond(Extract):
    lookup_name = 'second'


DateField.register_lookup(ExtractYear)
DateField.register_lookup(ExtractMonth)
DateField.register_lookup(ExtractDay)
DateField.register_lookup(ExtractWeekDay)
DateField.register_lookup(ExtractWeek)

TimeField.register_lookup(ExtractHour)
TimeField.register_lookup(ExtractMinute)
TimeField.register_lookup(ExtractSecond)

DateTimeField.register_lookup(ExtractHour)
DateTimeField.register_lookup(ExtractMinute)
DateTimeField.register_lookup(ExtractSecond)

ExtractYear.register_lookup(YearExact)
ExtractYear.register_lookup(YearGt)